Skip to content
Latchkey

How to Set an Environment Variable in GitLab CI

GitLab CI sets variables with variables: at global or job scope, and passes computed values via dotenv artifacts.

Use variables: for static values. To compute a value in one job and use it in a later one, write it to a .env file and expose it as a dotenv report artifact.

Static and dynamic variables

Global variables: apply to every job; job-level keys override them. Dotenv artifacts carry runtime values downstream.

.gitlab-ci.yml
variables:
  NODE_ENV: production

build:
  script:
    - echo "VERSION=$(cat VERSION)" >> build.env
  artifacts:
    reports:
      dotenv: build.env

deploy:
  needs: [build]
  script:
    - echo "Deploying $VERSION"

Gotchas

  • Project/group CI/CD variables (Settings > CI/CD) override file-defined ones and are the place for secrets.
  • Variables defined in script: with export do not persist to other jobs - use the dotenv artifact pattern.
  • Mark sensitive UI variables as "Masked" and "Protected" so they only reach protected branches and are hidden in logs.

Verify it actually works

Terminal
# validate the pipeline definition against your project's CI lint
curl -s --header "PRIVATE-TOKEN: $TOKEN" \
  "https://gitlab.com/api/v4/projects/$PROJECT_ID/ci/lint" \
  --data-urlencode "content=$(cat .gitlab-ci.yml)"

# then confirm which rules matched on a real pipeline
# CI/CD -> Pipelines -> the run -> each job -> "Trigger"

Frequently asked questions

How do I set an Environment Variable in GitLab CI?
Use variables: for static values. To compute a value in one job and use it in a later one, write it to a .env file and expose it as a dotenv report artifact.
Static and dynamic variables?
Global variables: apply to every job; job-level keys override them. Dotenv artifacts carry runtime values downstream.

Related guides

References

Run this faster and cheaper on Latchkey managed runners - self-healing included. Start free → 30-day trial · No credit card