my-notes

GitHub_Secrets_and_Environment_Variables

1 min read

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.



#github #secrets #environment #security

Built with mdgarden