How to Use Protected and File-Type Variables in GitLab CI/CD
Protected variables are exposed only on protected branches and tags, and file-type variables arrive as a path to a temp file.
Mark a CI/CD variable Protected so it is available only on protected refs, and set its type to File so tools that expect a path (like a kubeconfig or service-account key) can read it directly.
Steps
- In Settings to CI/CD to Variables, enable Protect for secrets used on protected branches.
- Set the variable Type to File for credentials that need a file path.
- Reference the variable as a path in the job.
Pipeline
.gitlab-ci.yml
deploy:
stage: deploy
rules:
- if: '$CI_COMMIT_REF_PROTECTED == "true"'
script:
# GCP_KEY is a File-type variable: $GCP_KEY is the path to the file
- gcloud auth activate-service-account --key-file "$GCP_KEY"
- ./deploy.shGotchas
- A protected variable is undefined on unprotected branches, so jobs there see an empty value.
- For a File-type variable the value IS the file path, not the contents; do not echo it into another file.
Related guides
How to Set Up Environments and Deployments in GitLab CI/CDTrack deployments in GitLab CI/CD with the environment keyword, recording deployed versions and exposing a li…
How to Build and Push to the GitLab Container Registry in GitLab CI/CDBuild an image and push it to the GitLab Container Registry from CI/CD, authenticating with the built-in CI_R…