GitLab CI/CD supports both custom variables and predefined variables. Use them to parameterize your pipeline and avoid hard-coding values.
1. Pain Point: Hard-Coded Values in Every Job
Here’s a typical pipeline that builds, tests, and pushes a Docker image. Notice how the registry, username, image name, and version are repeated in each job:imageName or version requires edits in multiple places.
2. Variable Scopes: Global vs. Job-Level
GitLab CI/CD provides two scopes for custom variables:| Scope | Declaration Location | Effective In |
|---|---|---|
| Global | top-level variables: block | All jobs |
| Job | variables: inside a job | That specific job |
- Global variables can be overridden by job-level variables with the same name.
- Job-level variables are isolated to their job and not visible elsewhere.
3. Defining Global Variables
Move shared configuration into a globalvariables: block. This makes your pipeline DRY and easier to update.
DEPLOY_SITEis available to both jobs.REVIEW_PATHapplies only todeploy_review_job.
4. Refactoring Docker Jobs with Shared Variables
First, here’s a version that still repeats variables at the job level:USERNAME, REGISTRY, IMAGE, and VERSION—we can improve this.
5. Promoting Common Variables to Global Scope
Define all shared variables at the top level. Only sensitive or job-specific variables stay within the job.PASSWORD remains in docker_push, while USERNAME, REGISTRY, IMAGE, and VERSION are defined once.
6. Leveraging Predefined CI/CD Variables for Dynamic Tagging
Instead of a staticlatest tag, use $CI_PIPELINE_ID or $CI_COMMIT_SHA to uniquely tag each build:
ascii-artwork:<pipeline_id>, making image versions traceable.
7. Viewing Expanded Variables in Job Logs
When the pipeline runs, GitLab replaces variables with their values:$VERSION was replaced by the numeric pipeline ID.
8. Job-Level Variables Are Isolated
Job-specific variables do not carry over to other jobs:$PASSWORD is empty because it was only defined in the docker_push job.
Avoid exposing sensitive variables in job logs. Use Masked Variables or Protected Variables to secure credentials and secrets.
9. Next Steps
- Explore GitLab CI/CD Variables documentation.
- Learn how to mask and protect variables.