Managing Variables and Secrets in GitLab CI
Best practices for managing CI/CD variables and secrets in GitLab. Covers masked variables, protected variables, group-level inheritance, and file-type variables.
Configuration
Detailed Explanation
Variables and Secrets in GitLab CI
GitLab CI provides multiple ways to define variables, each with different scope and security characteristics.
Variable Definition Levels
# Pipeline-level variables
variables:
APP_NAME: my-app
NODE_ENV: production
build:
# Job-level variables (override pipeline-level)
variables:
NODE_ENV: test
script:
- echo $APP_NAME
- echo $NODE_ENV # outputs "test"
Predefined Variables
GitLab provides 100+ predefined variables:
| Variable | Description |
|---|---|
$CI_COMMIT_SHA |
Full commit hash |
$CI_COMMIT_SHORT_SHA |
First 8 characters of the commit hash |
$CI_COMMIT_BRANCH |
Branch name |
$CI_COMMIT_TAG |
Tag name (empty if not a tag pipeline) |
$CI_REGISTRY |
Container registry URL |
$CI_REGISTRY_IMAGE |
Registry image path for this project |
$CI_PROJECT_DIR |
Full path of the repository clone |
$CI_PIPELINE_ID |
Unique pipeline ID |
Secret Management in Settings
Navigate to Settings > CI/CD > Variables to define secrets:
- Masked: Value is hidden in job logs. Only values matching a specific format can be masked.
- Protected: Only available in pipelines for protected branches/tags.
- File type: Creates a temporary file containing the value, with the variable pointing to the file path. Useful for certificates and JSON keys.
Dynamic Variables
build:
script:
- export VERSION=$(cat package.json | jq -r .version)
- echo "VERSION=$VERSION" >> build.env
artifacts:
reports:
dotenv: build.env
deploy:
needs:
- job: build
artifacts: true
script:
- echo "Deploying version $VERSION"
The dotenv report artifact passes dynamically computed variables to downstream jobs.
Security Best Practices
- Never echo secrets: Even masked variables can leak in error messages or debug output.
- Use protected variables for production: Ensures secrets are only available on protected branches.
- Rotate secrets regularly: Update CI/CD variables on a schedule.
- Prefer file-type for credentials: JSON keys and certificates are safer as files than environment strings.
Use Case
Variable management is fundamental to every GitLab CI pipeline. Use pipeline-level variables for non-sensitive configuration and GitLab UI variables for secrets like API keys, tokens, and credentials.