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:withexportdo 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
How to Set a Job Timeout in GitLab CISet a job timeout in GitLab CI with the timeout keyword, how it interacts with the project and runner
How to Trigger a GitLab CI Pipeline ManuallyTrigger a GitLab CI pipeline or job manually - when: manual jobs, manual gates with allow_failure, and the
How to Retry a Failing Job in GitLab CIAutomatically retry a failing GitLab CI job with the retry keyword - set max attempts and scope retries to