Lesson 07 intermediate

Environments and Deployments

Track where code runs with GitLab environments, deployment history and rollbacks, dynamic review apps per merge request, stop jobs and auto_stop_in, dotenv reports for dynamic URLs, resource_group to serialise deploys, protected environments and deployment approvals.

A deploy job that just runs a script works, but GitLab knows nothing about it. Which commit is on staging? Who deployed production last Tuesday? What was running before the bad release? Environments answer those questions. You add one keyword to a job and GitLab starts recording every deployment, shows links to the running app and gives you a one-click rollback.

Your first environment

deploy-staging:
  stage: deploy
  script:
    - ./scripts/deploy.sh staging
  environment:
    name: staging
    url: https://staging.orbit.example.com
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH

After the first successful run, open Operate → Environments. You see staging with:

  • the commit and merge request currently deployed;
  • who triggered it and when;
  • an Open button that goes to the url;
  • the full deployment history, newest first.

Jobs with environment are deployment jobs. GitLab records a deployment every time one runs, whether it succeeds or fails.

Environment tiers

GitLab guesses a tier from the name (production, staging, testing, development, other). Set it explicitly when your names are creative:

environment:
  name: live-eu
  deployment_tier: production

The tier feeds DORA metrics such as deployment frequency and lead time, and it is what security policies and approval rules usually key on.

A full staging to production flow

stages: [build, test, deploy]

deploy-staging:
  stage: deploy
  script: ./scripts/deploy.sh staging "$CI_COMMIT_SHORT_SHA"
  environment:
    name: staging
    url: https://staging.orbit.example.com
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH

deploy-production:
  stage: deploy
  needs: [deploy-staging]
  script: ./scripts/deploy.sh production "$CI_COMMIT_SHORT_SHA"
  environment:
    name: production
    url: https://orbit.example.com
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
      when: manual
  interruptible: false

Every merge to main lands on staging. Production waits for a click, and only after staging succeeded. That is continuous delivery from lesson 1, in about twenty lines.

Rollback

Open Operate → Environments → production. Each past deployment has a Re-deploy button. Clicking it re-runs the deploy job of that older pipeline, with that pipeline’s commit and artifacts.

This only works if your deploy job is repeatable from its own inputs: it should deploy the exact artifact or image tag built in its pipeline, not “whatever is latest”. That is why the example passes $CI_COMMIT_SHORT_SHA to the script. Lesson 8 tags images with the commit for the same reason.

Rolling back code does not roll back data. If the release ran a database migration, re-deploying old code may fail against the new schema. Write migrations that are backward compatible for at least one release (add columns before using them, remove them a release later).

Review apps: one environment per merge request

A dynamic environment uses variables in its name, so each branch gets its own. Reviewers open a running copy of the change instead of reading screenshots.

deploy-review:
  stage: deploy
  script:
    - ./scripts/deploy-review.sh "$CI_COMMIT_REF_SLUG"
  environment:
    name: review/$CI_COMMIT_REF_SLUG
    url: https://$CI_COMMIT_REF_SLUG.review.orbit.example.com
    on_stop: stop-review
    auto_stop_in: 3 days
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"

stop-review:
  stage: deploy
  script:
    - ./scripts/destroy-review.sh "$CI_COMMIT_REF_SLUG"
  environment:
    name: review/$CI_COMMIT_REF_SLUG
    action: stop
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
      when: manual
  allow_failure: true

How the pieces fit:

  • review/ in the name groups all review apps in a folder on the Environments page.
  • CI_COMMIT_REF_SLUG turns feature/Dark-Mode into feature-dark-mode, safe for a hostname.
  • on_stop names the job that tears the environment down. GitLab runs it automatically when the merge request is merged or closed, or when the branch is deleted.
  • auto_stop_in stops forgotten environments after three days of no new deployments.
  • The stop job uses action: stop, is manual so people can also stop it early, and allows failure so a teardown hiccup does not block the merge request.

The merge request page shows a View app button pointing at the review URL.

Dynamic URLs with dotenv

Sometimes you only learn the URL during the deploy, for example when a platform assigns a random hostname. Write it to a dotenv report and reference it in environment:url:

deploy-preview:
  script:
    - URL=$(./scripts/deploy-preview.sh)
    - echo "PREVIEW_URL=$URL" >> deploy.env
  artifacts:
    reports:
      dotenv: deploy.env
  environment:
    name: preview/$CI_COMMIT_REF_SLUG
    url: $PREVIEW_URL

Variables from a dotenv report also reach any later job that needs this one, which is the standard way to pass a value from one job to the next.

resource_group: one deploy at a time

Two pipelines finishing close together can run two production deploys at the same moment and leave the environment half one, half the other. A resource_group makes jobs that share it run one at a time, across all pipelines of the project:

deploy-production:
  resource_group: production
  environment:
    name: production

The second deploy waits until the first finishes. By default waiting jobs run in an unordered way; set the resource group’s process mode to oldest_first or newest_first through the API if order matters. newest_first is handy for staging, where only the latest commit is interesting.

Protected environments and approvals

On GitLab Premium and Ultimate you can protect an environment (Settings → CI/CD → Protected environments):

  • Allowed to deploy: only listed users, groups or roles can run jobs that target it. Everyone else sees the job but cannot start it.
  • Approvals: deployments wait for one or more approvers before the job starts. The pipeline shows the deployment as waiting for approval, and approvers act from the Environments page or the API.

On the Free tier, get most of the way with a protected main branch, a manual production job and protected variables scoped to production. Only maintainers can push to main, and only pipelines on main see the production credentials.

Environment-scoped variables in practice

Lesson 4 introduced environment scopes. With environments in place, use them:

VariableScopeValue
API_URLstaginghttps://staging-api.orbit.example.com
API_URLproductionhttps://api.orbit.example.com
API_URLreview/*https://review-api.orbit.example.com

The same deploy script reads $API_URL and gets the right value for whichever environment the job targets.

Exercise

Production is broken after today’s release. The deploy job deploys the image tag built in its own pipeline. What is the fastest safe rollback?

  1. Revert the commit and wait for a new pipeline to build and test it
  2. Re-deploy yesterday’s production deployment from Operate → Environments
  3. SSH into the server and edit the files back by hand
  4. Delete the production environment in GitLab
Show answer

Answer: B. Re-deploy re-runs the old pipeline’s deploy job with its own image tag, so production gets exactly what ran yesterday. Reverting the commit is still a good follow-up so main matches what is deployed.

Exercise

Why does the review app use name: review/$CI_COMMIT_REF_SLUG together with on_stop?

  1. So every merge request deploys to the same shared environment
  2. So each branch gets its own environment and it is torn down automatically when the merge request closes
  3. Because GitLab only allows environment names with a slash
  4. So the review app is deployed to production
Show answer

Answer: B. Variables in the name make one environment per branch, and on_stop names the job GitLab runs to clean it up when the merge request is merged, closed or the branch is deleted.

Key takeaways

  • Adding environment to a job turns it into a tracked deployment with history and a link.
  • Re-deploy gives one-click rollback when deploy jobs use their own pipeline’s artifacts.
  • Dynamic environments with on_stop and auto_stop_in give each merge request a review app that cleans up after itself.
  • resource_group prevents two deploys to the same place at once.
  • Protected environments and approvals (Premium) control who can deploy; protected branches and variables cover the basics on Free.

FAQ

Is an environment the same as a server?

No. It is GitLab’s record of a place you deploy to. It can be one server, a Kubernetes namespace, an S3 bucket or a whole cloud account. GitLab only knows what your deploy job tells it.

Why did my review app keep running after the merge request was merged?

The stop job must have the same environment name, action: stop, and rules that add it to the same pipelines as the deploy job. If the stop job is not in the pipeline, GitLab has nothing to run.

Can I deploy the same commit to several regions?

Yes. Use one job per region with environment names like production/eu and production/us, or parallel:matrix to generate them. Each shows up as its own environment in a production folder.

How do I see what is deployed where across many projects?

The environments dashboard and, on Premium, the operations and environments dashboards show deployments across projects. For Kubernetes, the GitLab agent can show the live state of workloads.

Does stopping an environment delete anything?

Only what your stop job’s script deletes. GitLab marks the environment as stopped; the actual teardown is your code.

↑ ↓ navigate Enter open Esc close