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:
nameandurl: the URL appears as a link in merge requests.deployment_tier: production, staging, testing, development or other.when: manualin 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: productionensures 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: manualRemember
- 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.