Skip to content

Instantly share code, notes, and snippets.

@philip-gai
Last active January 14, 2024 18:11
Show Gist options
  • Save philip-gai/2b21293b178aa6ea6903e99cc1c32c4f to your computer and use it in GitHub Desktop.
Save philip-gai/2b21293b178aa6ea6903e99cc1c32c4f to your computer and use it in GitHub Desktop.
GitHub Actions: Set a repo environment secret using the gh cli in 1-2 steps
# Prerequisites:
# - Create a secret with your PAT token. Permissions needed: repo (all) and read:org
# - Create the HELLO_WORLD secret in your environment with some dummy initial value
#
# Notes:
# - You can tell that it works because it masks the secret_body in the echo secret step after it creates the secret 😄
# - If you don't want to have to pass --repo to gh secret set, then put the actions/checkout@v2 step before the gh secret set step
name: gh-set-secret
on:
workflow_dispatch:
env:
pat_token: ${{ secrets.PAT_TOKEN }} # Permissions: repo (all) and read:org
secret_name: HELLO_WORLD
secret_body: "Hello World!"
secret_environment: sandbox
jobs:
gh-set-secret:
runs-on: ubuntu-latest
steps:
- name: gh auth login
shell: bash
run: gh auth login --with-token <<< $pat_token
- name: gh secret set env
shell: bash
run: |
repository='${{ github.repository }}'
gh secret set "$secret_name" --env "$secret_environment" --body "$secret_body" --repo $repository
gh-test-secret:
needs: [gh-set-secret]
runs-on: ubuntu-latest
environment:
name: sandbox
env:
secret: ${{ secrets.HELLO_WORLD }}
steps:
- name: echo secret
shell: bash
run: |
echo "Secret: $secret"
@philip-gai
Copy link
Author

philip-gai commented Mar 30, 2022

I noticed that gh auth login did not work as expected with the GH_TOKEN or the GITHUB_TOKEN set, so I updated the gist.
I also simplified and cleaned up some of it.

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