How to Use CI/CD Variables and Secrets in GitLab CI
GitLab exposes config through CI/CD variables: predefined ones like $CI_COMMIT_SHA, plus UI-defined masked and protected variables for secrets.
Reference predefined variables directly in script:, and define your own (Settings > CI/CD > Variables) as Masked and Protected for anything sensitive.
Use predefined and custom variables
Predefined variables describe the pipeline; UI variables like $DEPLOY_TOKEN carry secrets safely.
.gitlab-ci.yml
deploy:
script:
- echo "Commit: ${CI_COMMIT_SHA}"
- echo "Branch: ${CI_COMMIT_BRANCH}"
- curl -H "Authorization: Bearer ${DEPLOY_TOKEN}" https://api.example.com/deploy
rules:
- if: $CI_COMMIT_BRANCH == "main"Gotchas
- Mark secret variables Masked (hidden in logs) and Protected (only on protected branches/tags).
- Use File-type variables for multi-line secrets like PEM keys; GitLab gives you a path to the file.
- Forked MR pipelines do not receive protected variables, which prevents secret exfiltration.
Key takeaways
- Predefined variables expose pipeline context; UI variables hold secrets.
- Mark secrets Masked and Protected to keep them safe.
- File-type variables suit multi-line keys and certs.
Related guides
How to Deploy with Environments in GitLab CIDeploy with GitLab CI environments using the environment: keyword to track deployments, link to live URLs, an…
How to Pass Variables Between Jobs in GitLab CIPass variables between jobs in GitLab CI with dotenv report artifacts, so a value computed in one job becomes…