0
0
GitHow-ToBeginner · 4 min read

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

ActionDescriptionExample
Add SecretStore sensitive data in repo settingsSettings > Secrets > New repository secret
Reference SecretUse secret in workflow YAML${{ secrets.SECRET_NAME }}
Use Secret in EnvPass secret as environment variableenv: TOKEN: ${{ secrets.TOKEN }}
Avoid LoggingDo not print secrets directlyUse secrets only in commands, not echo
Secret ScopeSecrets can be repo or org levelChoose 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.