In GitHub Actions, secrets are used to store sensitive information like API keys, passwords, or tokens. Here are different ways to use secrets:
The most common way to use secrets is by referencing them in the env
section of a workflow.
Here, MY_SECRET
is an environment variable populated by the MY_SECRET
secret.
Example:
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Use a secret in an environment variable
run: echo "The secret is $MY_SECRET"
env:
MY_SECRET: ${{ secrets.MY_SECRET }}
You can reference a secret directly in a script or command:
But be aware that — directly exposing secrets can accidentally log them.
Example:
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Directly use a secret
run: echo "${{ secrets.MY_SECRET }}"
You can reference a secret directly in a script or command:
Secrets are often passed to third-party actions as inputs.
Here, secrets like DOCKER_USERNAME
and DOCKER_PASSWORD
are securely passed to the Docker build action.
For example:
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Push to DockerHub
uses: docker/build-push-action@v2
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
If you're running custom scripts in your workflow, pass secrets as environment variables:
Inside deploy.sh
, use $API_TOKEN
to access the secret.
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Run a custom script
run: ./deploy.sh
env:
API_TOKEN: ${{ secrets.API_TOKEN }}
Secrets can be scoped to specific environments.
For example, you might have different API keys for staging and production:
Only workflows targeting the production environment can access the PRODUCTION_API_KEY
secret.
jobs:
deploy:
runs-on: ubuntu-latest
environment: production
steps:
- name: Use production secret
run: echo "Deploying with key ${{ secrets.PRODUCTION_API_KEY }}"
Secrets can be used across multiple stages of a workflow, depending on their scope.
For example, you might build and deploy your app in separate jobs:
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Use secret in build
run: echo "Building with ${{ secrets.BUILD_KEY }}"
deploy:
needs: build
runs-on: ubuntu-latest
steps:
- name: Deploy using a secret
run: echo "Deploying with ${{ secrets.DEPLOY_KEY }}"
Secrets can also be used when creating reusable workflows or composite actions.
Pass secrets as inputs to ensure they are accessible within the action.