Automatically merge dependabot pull requests

A couple of weeks ago I added a small automation to automatically merge dependabot pull requests if the build succeed.

And I should have done this way sooner!


I mean, how many times you get a dependabot pull request, the build passes, and you decide not to merge it?

For me, its very rare.

What do happen a lot is me forgetting to merge one of these PRs, or ignoring them for way too long because I have too many other things to do.

So, I did this:

# .github/workflows/build.yml
name: build

on:
  push:
    branches:
      - main
  pull_request:

permissions:
  contents: read

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      -  # do your thing ...

  # this is the block that matters:
  dependabot:
    needs: [build] # <-- important!
    runs-on: ubuntu-latest
    permissions:
      pull-requests: write
      contents: write
    if: ${{ github.actor == 'dependabot[bot]' && github.event_name == 'pull_request'}}
    steps:
      - id: metadata
        uses: dependabot/fetch-metadata@v2
        with:
          github-token: "${{ secrets.GITHUB_TOKEN }}"
      - run: |
          gh pr review --approve "$PR_URL"
          gh pr merge --squash --auto "$PR_URL"          
        env:
          PR_URL: ${{github.event.pull_request.html_url}}
          GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}

What this does

  1. The dependabot job will only run after/if the build job succeeds
  2. It will also check that the current event is a pull request made by dependabot
  3. If all of these are true, it’ll approve and merge the pull request

Caveats

The only caveat is that you’ll need to enable “Allow GitHub Actions to create and approve pull requests” option in each repository:

GitHub settings to change

GitHub settings to change

Other than that, all good so far!


I should have done this way sooner!

It saves me time every day, as I don’t need to go merging every single dependabot PR there is (and when you maintain hundreds of repositories, there are always hundreds of issues/PRs to see).

I hope you enjoy this as much as me. See ya!