Environments, manual deploys and review apps

GitLab CI/CD · Advanced · 12 min

Knowing what is deployed where, and who may deploy to production, is central to safe continuous delivery.

Adding environment: to a job records a deployment each time it runs. GitLab shows environments under Operate, Environments with the currently deployed commit, history and a one-click re-deploy of an older successful job for rollbacks.

Key options:

  • name and url: the URL appears as a link in merge requests.
  • deployment_tier: production, staging, testing, development or other.
  • when: manual in rules, so production deploys wait for a click.
  • Protected environments (Settings, CI/CD) restrict who can run deploy jobs and can require approvals.
  • resource_group: production ensures only one deploy job for that group runs at a time, so two pipelines never deploy concurrently.

Review apps are dynamic environments created per branch or merge request, named with variables: name: review/$CI_COMMIT_REF_SLUG. A second job with action: stop tears it down; link it with on_stop, and GitLab runs it when the branch is deleted or the MR merges. auto_stop_in: 1 week cleans up forgotten ones.

Environment-scoped variables let the same job script deploy to staging or production with different credentials, chosen by the environment name.

Example

deploy-review:
  stage: deploy
  script: ./deploy.sh "$CI_COMMIT_REF_SLUG"
  environment:
    name: review/$CI_COMMIT_REF_SLUG
    url: https://$CI_COMMIT_REF_SLUG.review.example.com
    on_stop: stop-review
    auto_stop_in: 1 week
  rules: [{if: $CI_PIPELINE_SOURCE == "merge_request_event"}]

stop-review:
  stage: deploy
  script: ./teardown.sh "$CI_COMMIT_REF_SLUG"
  environment: {name: review/$CI_COMMIT_REF_SLUG, action: stop}
  rules: [{if: $CI_PIPELINE_SOURCE == "merge_request_event", when: manual}]

deploy-prod:
  stage: deploy
  script: ./deploy.sh production
  environment: {name: production, url: https://example.com}
  resource_group: production        # one deploy at a time
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
      when: manual

Remember

  • environment: records deployments and enables rollback by re-running old jobs
  • Protected environments and manual rules gate production
  • resource_group serializes deploys; on_stop cleans up review apps

Watch out for

  • Deploying production from two pipelines at once; add a resource_group.

Check yourself

  1. What does resource_group: production guarantee?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.gitlab.com/ci/environments/