How to Use GitHub Secrets for Secure Workflow Automation
Use
GitHub Secrets to securely store sensitive data like API keys in your repository settings. Access these secrets in your GitHub Actions workflows using the secrets context, for example, ${{ secrets.MY_SECRET }}, to keep credentials safe and out of your code.Syntax
GitHub Secrets are stored in your repository or organization settings and accessed in workflows using the secrets context. Use the syntax ${{ secrets.SECRET_NAME }} inside your workflow YAML file to reference a secret.
Example parts:
secrets: The context that holds all secrets.SECRET_NAME: The exact name of your secret as defined in GitHub.${{ }}: GitHub Actions expression syntax to evaluate the secret.
yaml
env:
API_KEY: ${{ secrets.API_KEY }}Example
This example shows how to use a GitHub secret named API_KEY in a workflow to print a masked message. The secret value is never shown in logs.
yaml
name: Example Workflow on: [push] jobs: print-secret: runs-on: ubuntu-latest steps: - name: Show secret usage run: echo "API key is $API_KEY" env: API_KEY: ${{ secrets.API_KEY }}
Output
API key is ***
Common Pitfalls
Common mistakes when using GitHub Secrets include:
- Trying to print secrets directly in logs, which GitHub masks but is still risky.
- Using incorrect secret names or typos, causing empty values.
- Not adding secrets to the repository or organization before referencing them.
- Committing secrets directly in code instead of using secrets.
Always verify secret names and avoid exposing secrets in output.
yaml
## Wrong way (exposes secret in logs): run: echo "My secret is $MY_SECRET" ## Right way (use secret as environment variable and avoid echoing it): run: some_command --token "$MY_SECRET" env: MY_SECRET: ${{ secrets.MY_SECRET }}
Quick Reference
| Action | Description | Example |
|---|---|---|
| Add Secret | Store sensitive data in repo settings | Settings > Secrets > New repository secret |
| Reference Secret | Use secret in workflow YAML | ${{ secrets.SECRET_NAME }} |
| Use Secret in Env | Pass secret as environment variable | env: TOKEN: ${{ secrets.TOKEN }} |
| Avoid Logging | Do not print secrets directly | Use secrets only in commands, not echo |
| Secret Scope | Secrets can be repo or org level | Choose scope when adding secret |
Key Takeaways
Store sensitive data in GitHub Secrets to keep it out of your code.
Access secrets in workflows using the syntax ${{ secrets.SECRET_NAME }}.
Never print secrets directly in logs to avoid accidental exposure.
Add secrets in repository or organization settings before use.
Use secrets as environment variables or command arguments securely.