Variables carry the branch, commit and settings into scripts, and almost every rule and script uses them.
Variables are environment variables available to job scripts. Define them with variables: at the top level (all jobs) or inside a job (that job only, overriding the global one).
GitLab sets many predefined variables in every job:
CI_COMMIT_SHA,CI_COMMIT_SHORT_SHA: the commit.CI_COMMIT_BRANCH: the branch name (not set for tag or merge request pipelines);CI_COMMIT_TAGfor tag pipelines;CI_COMMIT_REF_NAMEfor either.CI_DEFAULT_BRANCH: usuallymain.CI_PIPELINE_SOURCE: why the pipeline exists:push,merge_request_event,schedule,web,trigger,api...CI_PROJECT_DIR,CI_JOB_ID,CI_REGISTRY_IMAGE,CI_JOB_TOKEN.
Variables can also be defined in project, group or instance settings, for a schedule, or when running a pipeline manually. When the same name is defined in several places, settings-level and manually supplied variables beat YAML ones, and job-level YAML beats top-level YAML.
Variables can reference other variables (IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA). They are expanded by GitLab before the job runs in some keywords (like image or rules) and by the shell inside script. To see what a job receives, run export in a debug job, but never in projects with secrets.
Example
variables: # all jobs
APP_NAME: shop
IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA
show:
variables:
APP_NAME: shop-api # overrides the global value for this job
script:
- echo "$APP_NAME $IMAGE" # shop-api registry.gitlab.com/acme/shop:1a2b3c4d
- echo "source=$CI_PIPELINE_SOURCE branch=$CI_COMMIT_BRANCH"
# source=push branch=mainRemember
- variables: at top level or per job; job level wins
- CI_PIPELINE_SOURCE and CI_COMMIT_BRANCH drive most logic
- Settings and manual variables override YAML variables
Watch out for
- Using CI_COMMIT_BRANCH in a merge request pipeline: it is empty there; use CI_COMMIT_REF_NAME or CI_MERGE_REQUEST_SOURCE_BRANCH_NAME.