Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 44 ยท GitHub Actions in Practice

Environments, Approvals and Deployments

Protect deployments with GitHub environments: required reviewers, environment secrets, branch rules, OIDC cloud login without stored keys, and deploy concurrency.

Running tests is safe: the worst outcome is a red check. Deploying is different. A deploy job can change a live system, and it needs credentials powerful enough to do so. If every workflow run on every branch can reach those credentials, one careless pull request can ship to production. GitHub's answer is the environment: a named target such as staging or production that carries its own protection rules, secrets and history.

In this lesson you will create the mental model (what an environment is and what it guards), see how approvals, branch restrictions and environment secrets work, learn how OpenID Connect (OIDC) removes long-lived cloud keys from your repository, and use concurrency groups so two deploys never race. The workflow YAML is read-only. The stand-in is a state machine that shows how a deployment job moves through waiting, approval and running.

What an environment is

An environment is configured in the repository settings, not in YAML. A workflow job opts in by naming it:

YAML
jobs:
  deploy-staging:
    runs-on: ubuntu-latest
    environment: staging
    steps:
      - run: echo "Deploying to staging"

The moment a job says environment: staging, GitHub checks that environment's protection rules before the job is allowed to start. If every rule passes, the job runs, and it can now read the environment's secrets and variables. Each such run also creates a deployment record, which the repository's "Deployments" view and pull requests display (with a link to the live URL if you provide one), giving you a history of what was deployed where and when.

You can give an environment a URL that appears on the run page:

YAML
    environment:
      name: production
      url: https://shop.example.com

Environments usually mirror the stages your code passes through: dev, staging, production. The names are yours to choose.

Protection rules

Four kinds of rule are common. Availability of some of them depends on the repository's visibility and your GitHub plan, so check your own account before you rely on them in a private repository.

Rule What it does
Required reviewers Up to a handful of people or teams must approve before the job starts. Optionally the person who triggered the run cannot approve their own deployment.
Wait timer The job waits a fixed number of minutes after it is ready, giving time to cancel.
Deployment branches and tags Only runs from selected branches or tags (for example main and v*) may use the environment. Everything else is rejected.
Custom protection rules Third-party checks (monitoring, change windows) can approve or reject a deployment through an app.

Combined, they make a strong pattern: staging has no reviewers and deploys automatically from main; production requires a reviewer from the release team, accepts runs only from main and release tags, and can only be reached once the staging job has succeeded.

flowchart LR
    T["test"] --> S["deploy-staging<br/>no approval"]
    S --> A{"production:<br/>required reviewer"}
    A -- approved --> P["deploy-production"]
    A -- rejected --> X["run fails"]

The production job pauses at the approval gate; staging runs straight through.

YAML
name: Release

on:
  push:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: ./scripts/test.sh

  deploy-staging:
    needs: test
    runs-on: ubuntu-latest
    environment: staging
    steps:
      - uses: actions/checkout@v4
      - run: ./scripts/deploy.sh staging
        env:
          DEPLOY_TOKEN: ${{ secrets.DEPLOY_TOKEN }}

  deploy-production:
    needs: deploy-staging
    runs-on: ubuntu-latest
    environment:
      name: production
      url: https://shop.example.com
    steps:
      - uses: actions/checkout@v4
      - run: ./scripts/deploy.sh production
        env:
          DEPLOY_TOKEN: ${{ secrets.DEPLOY_TOKEN }}

Both deploy jobs use secrets.DEPLOY_TOKEN, yet they receive different values. That is the next feature.

Environment secrets and variables

Secrets and variables can be defined at three levels (see Secrets, Variables and Environment Variables): organization, repository and environment. An environment-level secret is delivered only to jobs that reference that environment, and only after its protection rules have passed. The same name can hold a staging value in staging and a production value in production; the YAML stays identical.

This is the real security value of environments. A job that does not name production cannot read production secrets, no matter what its script tries. A pull request that edits the workflow to print secrets.DEPLOY_TOKEN in a job without an approved environment gets nothing, and the required reviewer sees exactly which branch and workflow are asking for approval. Always read what you are approving: the approval covers the code of that run.

Passwordless cloud access with OIDC

Storing a cloud access key as a secret works, but the key is long-lived: it stays valid until someone rotates it, and it can be copied if it ever leaks. A better approach is OpenID Connect. Instead of a stored key, each job asks GitHub for a short-lived signed token (a JSON Web Token) that says who it is: which repository, branch, environment and workflow. The cloud provider is configured to trust GitHub's token issuer and to map specific claims to a role. The job exchanges the token for temporary cloud credentials that expire in about an hour.

To request the token, the job needs the id-token: write permission. This example shows the pattern for AWS; Google Cloud and Azure have equivalent official actions.

YAML
jobs:
  deploy-production:
    runs-on: ubuntu-latest
    environment: production
    permissions:
      id-token: write   # allow requesting the OIDC token
      contents: read
    steps:
      - uses: actions/checkout@v4

      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::123456789012:role/shop-deploy-production
          aws-region: eu-central-1

      - run: aws s3 sync ./dist s3://shop-example-production --delete

There are no keys anywhere in the repository. The security comes from the trust policy on the cloud role, which should require, for example, that the token's subject claim names this repository and the production environment. Then even a job on another branch or in another repository cannot assume the role. If you write the trust policy too loosely (for example "any repository in the organization"), the protection disappears, so be strict.

Granting id-token: write does not by itself give access to anything; the cloud-side trust policy does. Treat that policy as part of your deployment security and review it like code.

Concurrency: one deploy at a time

If two commits land minutes apart, two deploy runs can overlap and the older one may finish last, leaving production on the older version. A concurrency group serializes them:

YAML
jobs:
  deploy-production:
    runs-on: ubuntu-latest
    environment: production
    concurrency:
      group: deploy-production
      cancel-in-progress: false
    steps:
      - run: ./scripts/deploy.sh production

Only one job in the group deploy-production runs at a time. With cancel-in-progress: false, a newer job waits for the running one instead of killing it, which is what you want for deployments, since cancelling half way through a deploy can leave a system in an inconsistent state. Be aware of one limitation: GitHub keeps at most one pending run per group. If a third run arrives while one is running and one is queued, the queued one is cancelled in favor of the newest. For test and preview jobs cancel-in-progress: true is usually right, because only the newest commit matters.

Stand-in: an approval gate as a state machine

The behavior of a protected job is easy to describe as states: it is waiting for rules, becomes approved or rejected, then running and finally success or failed. The stand-in below models an environment with a branch rule, required reviewers and "no self-review", and runs three scenarios. It is a model of the idea, not GitHub's implementation.

JS Environment protection rules as a state machine

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The third scenario is the one many teams forget: the developer who pushed the change is also a listed reviewer, and "prevent self-review" stops them from approving their own deployment, so a second pair of eyes is guaranteed.

Practical advice

  • Use at least two environments, and make production the only one with required reviewers.
  • Restrict production to main and release tags, so an experimental branch can never deploy.
  • Prefer OIDC over stored cloud keys; if you must store a key, store it as an environment secret, not a repository secret.
  • Put deployment commands in versioned scripts (./scripts/deploy.sh) so the same logic works from a laptop in an emergency.
  • Plan rollbacks before you need them. Strategies such as blue-green and canary are covered in Deployment Strategies.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When does a job receive an environment's secrets?

    Environment secrets are released to a job after it has named the environment and every protection rule (such as required reviewers) has passed.
  2. 2. What does the id-token: write permission do in an OIDC deployment?

    The permission only allows the job to request an OIDC token. Access is decided by the cloud provider's trust policy matching the token's claims.
  3. 3. Why is cancel-in-progress: false usually right for deploy jobs?

    A newer deploy should wait for the current one to finish instead of interrupting it. Cancelling is better for tests and previews.
  4. 4. A feature branch workflow edits the YAML to print secrets.DEPLOY_TOKEN in a job that uses environment: production, restricted to main. What happens?

    The branch restriction is checked before the job starts. A branch that is not allowed cannot use the environment, so it never receives its secrets.
  5. 5. What is the most important property of the cloud role's trust policy in an OIDC setup?

    A loose policy lets jobs from unrelated repositories assume your role. Matching the repository and environment claims keeps access narrow.

Summary

  • An environment is a named deployment target with protection rules, secrets, variables and a deployment history; a job opts in with environment:.
  • Rules include required reviewers (with optional no-self-review), wait timers and allowed branches or tags.
  • Environment secrets reach a job only after its rules pass, so the same name can hold different values per environment.
  • OIDC replaces stored cloud keys with short-lived tokens; the cloud trust policy must match repository and environment claims.
  • A concurrency group with cancel-in-progress: false serializes deploys without interrupting one that is running.
  • Always read what you approve: the approval applies to that run's code.

Next, you will look at where your jobs actually run and what it costs: Self-Hosted Runners and Runner Costs.