Skip to content

Instantly share code, notes, and snippets.

@natanlao
Last active November 9, 2022 14:48
Show Gist options
  • Save natanlao/c84f43cf33f71f9c2a3f3cfdac42edfb to your computer and use it in GitHub Desktop.
Save natanlao/c84f43cf33f71f9c2a3f3cfdac42edfb to your computer and use it in GitHub Desktop.
Automatically merging Dependabot PRs

The best way I've found to automatically merge Dependabot PRs is to use actions/github-script to comment @dependabot merge on Dependabot PRs. There are a few reasons why I think this approach makes sense:

  • Commenting @dependabot merge on a Dependabot PR instructs Dependabot to merge the PR after tests (if any) pass, so we don't need to encode that dependency in a workflow file.

  • Unlike using an auto-merge action, nothing happens if the workflow runs on a false-positive non-Dependabot PR (i.e., if a PR that is not supposed to be auto-merged is auto-merged). In the case of a false positive, the worst case scenario is either (1) the false positive PR is from Dependabot, and an unwanted dependency update is merged, or (2) the false positive PR is not from Dependabot, and nothing is merged.

  • The obvious alternative, merging the pull request directly, also requires a personal access token with the public_repo scope at minimum.

It's worth noting that GitHub has explicitly refused to implement native auto-merge functionality in Dependabot, as it could lead to the rapid propagation of a compromised dependency. This remains a risk with this approach; to this end, auto-merge functionality should be as narrowly-scoped as possible (see jobs.automerge.if in the example below).

Note that in the example workflow, PRs are never checked out, which means that repository write access and workflow secrets stored in memory during a workflow invocation are insulated from any malicious code an attacker may introduce in a PR. See this GitHub blog post for more details.

name: Auto-merge Dependabot PRs

on:
  pull_request_target:
    branches: [ main ]
    types: [ labeled ]

jobs:
  automerge:
    runs-on: ubuntu-latest
    if: |
      github.actor == 'dependabot[bot]'
      && startsWith(github.ref, 'dependabot/pip/foo')
    steps:
    - name: Auto-merge Dependabot PRs
      uses: actions/github-script@v3
      with:
        # PAT with public_repo scope
        github-token: "${{ secrets.AUTOMERGE_PAT }}"
        script: |
          github.issues.createComment({
            issue_number: context.issue.number,
            owner: context.repo.owner,
            repo: context.repo.repo,
            body: '@dependabot merge (automerge)'
          })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment