
Module 3 Lesson 2: Environments and Variables
Protect your secrets. Learn how to use GitLab variables to store database passwords and API keys securely, and how to define different 'Environments' for Staging and Production.
Module 3 Lesson 2: Environments and Variables
You should NEVER type a password or a secret key directly into your .gitlab-ci.yml file. If you do, anyone who can see your code can steal your keys.
1. CI/CD Variables
GitLab allows you to store secret strings in the Settings menu.
- Go to Settings -> CI/CD -> Variables.
- Add a variable like
DB_PASSWORD. - In your YAML, you access it like a normal bash variable:
$DB_PASSWORD.
2. Protected vs. Masked Variables
- Protected: This variable is only available on "Protected" branches (like
main). Use this for your Production passwords. - Masked: GitLab will hide the value of this variable in the job logs. Even if your script accidentally runs
echo $DB_PASSWORD, the log will just show[masked].
3. Environments
GitLab allows you to track where your code is running.
deploy_prod:
stage: deploy
environment:
name: production
url: https://my-app.com
script:
- echo "Deploying to $CI_ENVIRONMENT_URL..."
Why use this?
- The Environments Dashboard shows you exactly which version of the code is running in "Staging" vs "Production."
- It provides an "Easy Button" to roll back to a previous version if a deployment fails.
4. Built-in (Predefined) Variables
GitLab provides dozens of variables for free:
$CI_COMMIT_BRANCH: The name of the branch being built.$CI_PIPELINE_ID: A unique number for this run.$CI_PROJECT_NAME: The name of your folder.
Exercise: The Secret Handshake
- Go to your GitLab project and add a variable:
SNEAKY_KEY="Banana". - Turn on "Masking" for this variable.
- Add a job to your YAML:
show_key: script: - echo "The key is $SNEAKY_KEY" - Run the pipeline. Check the logs. Did it show "Banana" or "[masked]"?
- Why is the "Protected" setting important for a team with 50 junior developers?
Summary
Variables and Environments turn a "Dumb Script" into a "Smart Pipeline." By decoupling your secrets from your code, you ensure that your platform remains secure even if your source code is compromised.
Next Lesson: Passing the baton: Working with Artifacts.