GitLab CI Environment Variable Not Passing Fix
In this tutorial, you'll learn about GitLab CI Environment Variable Not Passing Fix. We cover key concepts, practical examples, and best practices.
Your downstream job gets VERSION as empty even though the upstream job set it — GitLab CI variables set in one job are not automatically available to another job.
The Problem
# WRONG — setting variable in one job, expecting it in another
build:
script:
- export VERSION=$(date +%Y%m%d)
- echo "Version: $VERSION"
deploy:
script:
- echo "Deploying version $VERSION"
$ echo "Deploying version $VERSION"
Deploying version
VERSION was set as a shell variable in the build job. Each GitLab CI job runs in an isolated shell — variables don't persist between jobs.
Step-by-Step Fix
1. Use dotenv artifacts to pass variables
build:
script:
- echo "VERSION=$(date +%Y%m%d)" > build.env
artifacts:
reports:
dotenv: build.env
deploy:
needs: [build]
script:
- echo "Deploying version $VERSION"
2. Use CI/CD variables defined in the UI
deploy:
script:
- echo "Deploying to $DEPLOY_ENV"
variables:
DEPLOY_ENV: production
Set variables in Settings > CI/CD > Variables with the appropriate scope (project, group, or instance).
3. Use needs: with variables from upstream jobs
build:
variables:
APP_VERSION: "1.0.0"
script:
- echo "Building $APP_VERSION"
test:
needs: [build]
script:
- echo "Testing $APP_VERSION"
4. Use extend for shared variables
.shared-variables:
variables:
REGISTRY: registry.example.com
IMAGE_NAME: myapp
build:
extends: .shared-variables
script:
- docker build -t $REGISTRY/$IMAGE_NAME:$CI_COMMIT_SHA .
deploy:
extends: .shared-variables
script:
- docker push $REGISTRY/$IMAGE_NAME:$CI_COMMIT_SHA
Expected output:
build: Version: 20260624
deploy: Deploying version 20260624
Prevention Tips
- Use
dotenvartifacts to pass variables between jobs - Use CI/CD variables for environment-wide config
- Use
variables:at the job level for job-specific overrides - Use
extendswith.shared-variablesfor reusable config - Prefix custom variables consistently (e.g.,
APP_,DEPLOY_)
Common Mistakes with ci environment
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
These mistakes appear frequently in real-world GITLAB code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro