GitHub_Secrets_and_Environment_Variables
GitHub Secrets and Environment Variables
Manage sensitive data in workflows.
π Types of Secrets
| Type | Scope | Where Set |
|---|---|---|
| Repository | Single repo | Settings β Secrets |
| Environment | Specific env | Environment settings |
| Organization | All org repos | Org settings |
β Add Secrets
Add via CLI
gh secret set API_KEY
Prompts for value interactively.
Add with Value
gh secret set API_KEY --body "your-api-key-value"
Sets secret directly.
Add from File
gh secret set API_KEY < key.txt
Sets secret from file.
Add for Environment
gh secret set API_KEY --env production
Sets secret for specific environment.
Add for Organization
gh secret set ORG_SECRET --org my-org
Sets organization-level secret.
π List Secrets
List Repository Secrets
gh secret list
Shows secret names (not values).
List Environment Secrets
gh secret list --env production
Shows secrets for environment.
ποΈ Delete Secrets
Delete Secret
gh secret delete API_KEY
Removes secret.
Delete Environment Secret
gh secret delete API_KEY --env production
Removes environment secret.
π Use Secrets in Workflows
Environment Variable
steps:
- run: echo "Deploying..."
env:
API_KEY: ${{ secrets.API_KEY }}
Sets as environment variable.
In Step Input
- uses: some-action@v1
with:
api-key: ${{ secrets.API_KEY }}
Passes to action input.
Conditional on Secret
- name: Deploy if key exists
if: ${{ secrets.DEPLOY_KEY != '' }}
run: deploy
Checks if secret exists.
π§ Environment Variables
Set Repository Variable
gh variable set NODE_ENV --body "production"
Sets repository variable.
List Variables
gh variable list
Shows repository variables.
Use Variables in Workflow
env:
NODE_ENV: ${{ vars.NODE_ENV }}
Uses repository variable.
π .env Files
Use dotenv
- name: Load .env
run: |
set -a
source .env
npm run build
Loads local .env file.
β οΈ Security Best Practices
Never Echo Secrets
# β BAD - exposes secret
- run: echo ${{ secrets.API_KEY }}
# β
GOOD - use in env
- run: ./deploy.sh
env:
API_KEY: ${{ secrets.API_KEY }}
Mask Custom Values
- run: |
echo "::add-mask::$CUSTOM_SECRET"
Masks value in logs.
π‘ Tips
Secrets are Masked
GitHub automatically masks known secrets in logs.
Fork PRs
Secrets aren't available to workflows from forks.
Rotate Secrets
Regularly update secrets for security.
π Related
#github #secrets #environment #security