Skip to content

Instantly share code, notes, and snippets.

@EricCrosson
Forked from swinton/README.md
Created February 19, 2023 01:02
Show Gist options
  • Save EricCrosson/b25f8ec783a20b8cae63be7708fbd8b8 to your computer and use it in GitHub Desktop.
Save EricCrosson/b25f8ec783a20b8cae63be7708fbd8b8 to your computer and use it in GitHub Desktop.
Automatically sign your commits from GitHub Actions, using the REST API

Verified commits made easy with GitHub Actions

image

So you want to commit changes generated by a GitHub Actions workflow back to your repo, and have that commit signed automatically?

Here's one way this is possible, using the REST API, the auto-generated GITHUB_TOKEN, and the GitHub CLI, gh, which is pre-installed on GitHub's hosted Actions runners.

You don't have to configure the git client, just add a step like the one below... Be sure to edit FILE_TO_COMMIT and DESTINATION_BRANCH to suit your needs.

    # Use the REST API to commit changes, so we get automatic commit signing
    - name: Commit changes
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        FILE_TO_COMMIT: data.csv
        DESTINATION_BRANCH: data
      run: |
        export TODAY=$( date -u '+%Y-%m-%d' )
        export MESSAGE="chore: regenerate $FILE_TO_COMMIT for $TODAY"
        export SHA=$( git rev-parse $DESTINATION_BRANCH:$FILE_TO_COMMIT )
        export CONTENT=$( base64 -i $FILE_TO_COMMIT )
        gh api --method PUT /repos/:owner/:repo/contents/$FILE_TO_COMMIT \
          --field message="$MESSAGE" \
          --field content="$CONTENT" \
          --field encoding="base64" \
          --field branch="$DESTINATION_BRANCH" \
          --field sha="$SHA"

Caveats

Because of the underlying REST API, only 1 file can be committed at a time.

Notes

This is made possible because GitHub automatically signs commits from bots over the REST API. Since the GITHUB_TOKEN is a bot token, this also applies to commits from GitHub Actions.

See this blog post from 2019 for more details: https://github.blog/2019-08-15-commit-signing-support-for-bots-and-other-github-apps/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment