Skip to content

Lesson 5 of 9 · 24m

Environments and Controlled Deployments

Model staging and production honestly, use deployment jobs and protected environments, and keep rollbacks operationally real.

Deployment is where CI stops being a test harness and becomes an operational control plane. GitLab environments are not just labels. They connect jobs, URLs, deployment history, approvals, and rollback context. If you treat them as decorative metadata, you lose most of their value.

Declare what is being deployed where

deploy-staging:
  stage: deploy
  script:
    - ./scripts/deploy staging "$CI_COMMIT_SHA"
  environment:
    name: staging
    url: https://staging.sudosecurity.example
  rules:
    - if: '$CI_COMMIT_BRANCH == "main"'

The environment name should be stable. Do not create staging-123, staging-124, and endless copies unless they are truly independent review environments. Stable environments give you a useful deployment timeline.

production is an authorization boundary

A production deployment should not be one accidental push away from execution. Use protected environments, manual jobs, or approval rules appropriate to your risk level.

deploy-production:
  stage: deploy
  script:
    - ./scripts/deploy production "$CI_COMMIT_SHA"
  environment:
    name: production
    url: https://app.example.com
  when: manual
  rules:
    - if: '$CI_COMMIT_BRANCH == "main"'

when: manual means a human starts it, but it does not prove the human is authorized. Protected branches and protected environments enforce who can run or approve the job. Know the difference.

Rollback is a deployment path, not a hope

The best rollback is usually deploying a known-good commit forward. GitLab can expose rollback actions in the UI, but your script still has to know how to deploy that SHA. Test rollback before you need it.

deploy-production:
  script:
    - ./scripts/deploy production "$APP_VERSION"
  variables:
    APP_VERSION: $CI_COMMIT_SHA

If deployment uses mutable tags such as latest, rollback becomes guesswork. Immutable references — commit SHA, content digest, release version — make rollback boring, which is the goal.

Deployment data belongs in the job trace

Log the target, version, migration state, and health check result. Do not print secrets. A deployment job that only says done is operationally useless at 2 a.m.

echo "deploying $APP_VERSION to production"
./scripts/deploy production "$APP_VERSION"
./scripts/wait-for-health https://app.example.com/healthz 180

Field notes

  • Environment names should represent durable targets, not random job instances.
  • Manual approval controls who starts work; protected environments control who is allowed.
  • Rollback must use immutable versions and a tested deployment path.
  • Health checks belong inside deployment jobs, not as an undocumented human habit.
  • Never treat a green deployment job as proof of user-visible health without a check.

Was this lesson helpful?

Sign in to rate