Keep secrets safe in a pipeline
In this task you'll use secrets in a pipeline without leaking them into logs or pull requests.
GitHub secrets are encrypted values you read with ${{ secrets.NAME }}. They're stored at organisation, repository or environment level; environment secrets are only given to jobs that name that environment, so production keys stay with production jobs. GitHub masks secret values in logs, printing ***.
Masking only catches the value and a few common encodings of it (GitHub also hides base64 copies). If a step changes it in another way (hex, part of a URL, a value fetched at run time), mask the new form with ::add-mask::. Better still, avoid stored secrets: sign in to clouds with OIDC, and keep secrets out of the repository with push protection, which blocks a push that contains a known key format. Pull requests from forks don't get secrets at all.
Example. A build at Harbourline Design printed a storage connection string because a script hex-encoded it before logging, which the mask didn't recognise. The team added add-mask for the encoded value and moved the deploy to OIDC.
Before you start
You need: A free GitHub account and a public test repository (Actions minutes are free for public repositories). Time: 25 minutes.
Where to look
- Repository
- Settings
- Secrets and variables
- Actions
Steps
- Add a repository secret named
DEMO_TOKENwith a made-up test value:gh secret set DEMO_TOKEN(you type the value).Never use a real key for this. - Add
.github/workflows/secrets.ymlfrom Commands and push. - In the log, see the plain echo shows
***, but the hex line shows the encoded value in full.GitHub now also hides base64 copies of secrets, so this example uses hex. - Uncomment the add-mask line, push again, and see the encoded value hidden too.
- Turn on push protection under Settings, Advanced Security if it isn't already on.
Commands
jobs:
demo:
runs-on: ubuntu-latest
env:
TOKEN: ${{ secrets.DEMO_TOKEN }}
steps:
- run: echo "plain=$TOKEN"
- run: |
HEX=$(printf '%s' "$TOKEN" | od -An -tx1 | tr -d ' \n')
# echo "::add-mask::$HEX"
echo "hex=$HEX"
gh secret set DEMO_TOKEN
gh secret delete DEMO_TOKEN
Watch out for
- Cost
- Free.
- Security
- Masking is a safety net, not a control: anyone who can edit a workflow on a branch can send a secret elsewhere. Protect production secrets with environments and required reviewers.
- Common mistakes
- Echoing secrets to check them, putting them in workflow inputs or artifacts, and passing all secrets to reusable workflows.
Clean up
Delete the test secret: gh secret delete DEMO_TOKEN.
Words to know
- Secret
- An encrypted value a workflow can read but GitHub hides in logs.
- Environment secret
- A secret given only to jobs that use that environment.
- add-mask
- A workflow command that hides an extra value in logs.
- Push protection
- Blocks pushes that contain known secret formats.
Tick off each step and track your progress in the guide.
Open this task in DevOps, Hands On