Variables and Environment Configuration
What You'll Learn
You'll learn how to define and manage variables at different scopes in GitLab CI/CD pipelines to handle environment-specific configurations and dynamic behavior.
Understanding Variables in GitLab CI/CD
Think of variables as labeled containers for values you'll reuse throughout your pipeline—like naming your coffee preferences once instead of describing "medium roast, two sugars, splash of milk" every single time.
Pipeline-Level Variables
Pipeline-level variables are defined at the top of your .gitlab-ci.yml file and available to all jobs:
variables:
APP_VERSION: "1.2.3"
BUILD_ENV: "production"
These act as global settings—every job can access $APP_VERSION and $BUILD_ENV.
Job-Level Variables
Job-level variables override pipeline-level ones and apply only to that specific job:
build_job:
variables:
BUILD_ENV: "staging"
script:
- echo "Building for $BUILD_ENV"
Here, BUILD_ENV becomes "staging" for build_job only, while other jobs still see "production."
Environment-Specific Configuration
Variables enable different behavior per environment without duplicating code:
variables:
DATABASE_URL: "postgres://prod-db"
deploy_staging:
variables:
DATABASE_URL: "postgres://staging-db"
script:
- echo "Deploying to $DATABASE_URL"
This pattern lets you maintain one pipeline definition while deploying to multiple environments with different configurations—exactly what you learned about in environment promotion strategies.
Using Variables in Scripts
Reference variables with $VARIABLE_NAME in your scripts. They behave like regular shell environment variables, seamlessly integrating with commands you already know.
Key Takeaway: Variables in GitLab CI/CD provide flexible, reusable configuration at pipeline and job levels, enabling environment-specific behavior without code duplication—essential for managing multi-environment deployments efficiently.