Chapter 11: Ansible Introduction
11.8 Variables, vault awareness and secrets
Why: the problem
Suppose we are at Paytm and the playbook has the database password written inside it. The repo is shared with 60 people and a contractor. One copy leaks and the database is open. Variables let you keep values outside tasks. Ansible Vault encrypts secret files, so Git holds only scrambled text. And for CI, the secret can come from an environment variable at run time.
What we will build
You will use variables at three levels (group_vars, play vars, -e), encrypt a secrets file with Ansible Vault, and pass a password from an environment variable, then check that nothing secret is printed with no_log.
What: every term in plain English
- Variable — A named value, like app_port, used as {{ app_port }}.
- Precedence — Which value wins when the same name is set in two places. -e wins over all.
- Ansible Vault — A built-in tool that encrypts files with a password.
- vault password file — A file or script that gives the vault password, kept outside Git.
- no_log — Hides a task's values from output and logs.
- lookup env — Reads a value from an environment variable on the control node.
How: step by step
-
Make a secrets file
mkdir -p inventory/group_vars/db && vim inventory/group_vars/db/vault.ymlWhat it does: Put vault_mysql_password: CHANGE_ME in it.
Output
(file edit) -
Encrypt it
ansible-vault encrypt inventory/group_vars/db/vault.ymlWhat it does: Asks for a new vault password.
Output
New Vault password: Confirm New Vault password: Encryption successful -
Look at the file
head -2 inventory/group_vars/db/vault.ymlWhat it does: It is scrambled.
Output
$ANSIBLE_VAULT;1.1;AES256 62313365396662343061393464336163383764373764613633653634306231386433626436623361 -
Read it safely
ansible-vault view inventory/group_vars/db/vault.ymlWhat it does: Shows plain text only on your screen.
Output
vault_mysql_password: CHANGE_ME -
Run with the vault password
ansible-playbook db.yml --ask-vault-passWhat it does: Ansible decrypts in memory.
Output
Vault password: PLAY RECAP db1 : ok=3 changed=1 -
Run in CI with a password file
ansible-playbook db.yml --vault-password-file "$VAULT_PASS_FILE"What it does: CI writes the secret to a temp file path given as an env value.
Output
db1 : ok=3 changed=0 -
Override at run time
ansible-playbook web.yml -e app_port=8080What it does: Extra vars win over everything.
Output
TASK [debug] => "app_port": "8080"
Example 1: Variables at three levels, and who wins
Stack. debug module
Goal. Variables at three levels, and who wins.
inventory/group_vars/web.yml
app_port: 3000
vars_demo.yml
- hosts: web
vars:
app_port: 4000
tasks:
- name: Which port wins?
ansible.builtin.debug:
msg: "port is {{ app_port }} on {{ inventory_hostname }}"
What each line does
group_vars/web.yml— Weak: inventory level.play vars— Stronger than group_vars.-e app_port=8080— Strongest of all.
Green output
$ ansible-playbook vars_demo.yml
ok: [web1] => { "msg": "port is 4000 on web1" }
$ ansible-playbook vars_demo.yml -e app_port=8080
ok: [web1] => { "msg": "port is 8080 on web1" }
Expected result. Play vars beat group_vars, and -e beats both.
Example 2: MySQL user with a vaulted password and no_log
Stack. MySQL 8, community.mysql, Ansible Vault
Goal. MySQL user with a vaulted password and no_log.
inventory/group_vars/db/vars.yml
mysql_app_user: badge
mysql_app_password: "{{ vault_mysql_password }}"
db.yml
- hosts: db
become: true
tasks:
- name: App database user
community.mysql.mysql_user:
name: "{{ mysql_app_user }}"
password: "{{ mysql_app_password }}"
priv: "badges.*:ALL"
host: "10.0.1.%"
login_unix_socket: /var/run/mysqld/mysqld.sock
no_log: true
What each line does
vars.yml points to vault_ name— Plain file says where the value is; vault file holds it.no_log: true— Password never appears in output.host: "10.0.1.%"— Only app subnet can log in.
Green output
$ ansible-playbook db.yml --ask-vault-pass
TASK [App database user] *******************************
changed: [db1] => {"censored": "the output has been hidden due to the fact that 'no_log: true' was specified for this result"}
Expected result. User created; password is safe in Git and in logs.
Example 3: AWS RDS and DynamoDB settings for a Python app, secrets from env only
Stack. Python app, AWS RDS MySQL, DynamoDB, IAM role
Goal. AWS RDS and DynamoDB settings for a Python app, secrets from env only.
app_env.yml
- hosts: web
become: true
vars:
rds_host: badges.abcd1234.ap-south-1.rds.amazonaws.com
dynamo_table: reels-likes
tasks:
- name: App env file
ansible.builtin.copy:
dest: /etc/reels-api.env
content: |
DB_HOST={{ rds_host }}
DB_PASSWORD={{ lookup('env', 'RDS_PASSWORD') }}
DYNAMO_TABLE={{ dynamo_table }}
AWS_REGION=ap-south-1
owner: root
group: www-data
no_log: true
What each line does
lookup('env','RDS_PASSWORD')— Read from the shell or CI secret, not from a file.no AWS keys— The server uses an IAM role to call DynamoDB.group: www-data— The app user can read the file.
Green output
$ export RDS_PASSWORD="CHANGE_ME"
$ ansible-playbook app_env.yml
TASK [App env file] ************************************
changed: [web1] => {"censored": "the output has been hidden ..."}
Expected result. The app gets its settings; Git never sees the password.
Verify: did it work?
-
Vault file is encrypted
head -c 14 inventory/group_vars/db/vault.ymlWhat it does: Must start with $ANSIBLE_VAULT.
Output
$ANSIBLE_VAULT -
No secret in Git
git grep -n "CHANGE_ME" -- ":!*.md" | wc -lWhat it does: Expect 0 plain hits.
Output
0 -
Password works
ansible db -m community.mysql.mysql_query -a "query='select 1' login_user=badge login_password={{ mysql_app_password }}" --ask-vault-passWhat it does: Login works.
Output
db1 | SUCCESS
When it is red 1
ERROR! Attempting to decrypt but no vault secrets found
Cause. The file is encrypted and you gave no password.
Fix, step by step
- Add --ask-vault-pass.
- Or --vault-password-file pointing to a file outside Git.
When it is red 2
ERROR! Decryption failed (no vault secrets were found that could decrypt)
Cause. Wrong vault password.
Fix, step by step
- Check the password with ansible-vault view.
- Rekey with ansible-vault rekey if it must change.
When it is red 3
fatal: [db1]: FAILED! => {"msg": "'vault_mysql_password' is undefined"}
Cause. vault.yml is not in the right group_vars folder.
Fix, step by step
- Put it in group_vars/db/vault.yml.
- Run ansible-inventory --host db1 --ask-vault-pass to check.
Cleanup
-
Unset the lab secret
unset RDS_PASSWORDWhat it does: Remove it from your shell.
Output
(no output)
Ravindra Bagale's Tip
Never put a password in Git. Use Vault or an env variable.
Password Git मध्ये कधीही नको. Vault किंवा env variable वापरा.
Password Git में कभी नहीं. Vault या env variable इस्तेमाल करो.
Practice tasks
Easy Show precedence
Why: Know who wins.
What to do: Set app_port in group_vars, play vars and -e, and print it.
- Use the debug module.
Check: You can name the winner each time.
Medium Vault one file
Why: Practice encryption.
What to do: Encrypt vault.yml and run a play with it.
- ansible-vault encrypt
- --ask-vault-pass
Check: Run works and file is scrambled.
Easy Say variables and vault in two lines
Why: If you can say it simply, you understand it. Interviewers and juniors both need the short version first.
What to do: Write two short lines about variables and vault for a fresher who knows only Linux basics.
- Write the problem it solves.
- Write the one command or file you use for it.
- Read it aloud to a friend.
Check: A fresher understands it without asking a question.
Easy Start a two-server Ansible lab
Why: Practice needs safe throwaway servers. If you break them, you delete them and start again in one minute.
What to do: Start two Ubuntu containers that accept SSH, and one control machine with Ansible.
- python3 -m pip install --user ansible-core
- docker run -d --name web1 -p 2221:22 lscr.io/linuxserver/openssh-server
- docker run -d --name web2 -p 2222:22 lscr.io/linuxserver/openssh-server
- ansible --version
Check: ansible --version prints a core version, and ssh to both ports works.
Medium Do it on the second setup
Why: The idea must work on a VM, a container and a cloud server. Only the inventory should change, never the playbook.
What to do: Repeat this lesson on a different target than the one you used first.
- If you used containers, use one EC2 or local VM now.
- Change only the inventory file.
- Run the same playbook.
Check: Same result, and you changed only the inventory.
Medium Break it on purpose
Why: You must know the red output by face. On a real outage there is no time to read slowly.
What to do: Cause one error from the "When it is red" part of this lesson and fix it.
- Follow the error section.
- Copy the exact message into your notes.
- Write the fix in one line.
Check: You fixed it using the steps, without searching the web.
Medium Run it twice and read the recap
Why: Idempotence is the heart of Ansible.
What to do: Run your playbook or command two times and compare the PLAY RECAP lines.
- Run once and note changed=.
- Run again with no edits.
- Explain any task that still says changed.
Check: The second run shows changed=0, or you can explain every change.
Medium Write a runbook page
Why: At 2 a.m. nobody remembers flags. A short written page saves the on-call person.
What to do: Write a one-page runbook for this lesson.
- Title, when to use, exact commands, how to check, how to undo.
Check: A teammate can follow it alone.
Hard Explain it like an interview
Why: Interviewers want real stories, not definitions.
What to do: Record a 60 second answer about this lesson.
- Say the problem, the playbook or command, and one error you hit.
Check: Your answer has a real command and a real error message.
Hard Draw the flow top to bottom
Why: A drawing shows the order of work.
What to do: Draw this lesson as boxes from top to bottom.
- Start at your laptop, go through SSH, end at the check on the server.
Check: Each box matches a real step you ran.
Homework: try at home
Try at home
At home, put one fake password in a vault file, use it in a task with no_log, and check git diff shows only scrambled text.
Recap
- Put values in variables, not inside tasks.
- -e wins over all; defaults lose to all.
- Encrypt secrets with Ansible Vault or read them from env.
- Use no_log on tasks that touch secrets.
- Keep the vault password outside Git.
FAQ
Why the vault_ prefix?
So a plain vars file can show which variables exist without showing values.
Can I encrypt only one value?
Yes, with ansible-vault encrypt_string.
Vault or AWS Secrets Manager?
Both are fine. Lookups can read from Secrets Manager or HashiCorp Vault at run time.
Does no_log slow anything?
No, it only hides output.
Can I change the vault password?
Yes, ansible-vault rekey.
Can I see a vault file diff in Git?
Yes. Set a textconv for vault files so git diff shows plain text locally, while the repo keeps it encrypted.
Interview questions
-
How do you manage secrets in Ansible?
Ansible Vault for files or strings, or lookups to a secret manager or env, plus no_log on tasks.
-
Explain variable precedence briefly.
Role defaults lowest, then inventory vars, play vars, role vars, task vars, set_fact, and extra vars highest.
-
What is encrypt_string?
It encrypts a single value to paste into a YAML file.
-
How does CI give the vault password?
A CI secret is written to a temp file and passed with --vault-password-file, then deleted.
-
Why no_log?
So passwords do not appear in console output, CI logs or callbacks.
-
What happens if the vault password leaks?
Rotate the real secrets first, then rekey the vault files with a new password and update CI.
Quick quiz
Q1. Which variable source wins over all?
-e extra vars
Q2. What does ansible-vault encrypt do?
Encrypts a file with a password.
Q3. How do you hide a task value from logs?
no_log: true
Q4. Where should the vault password live?
Outside Git, typed or in a CI secret.
Q5. How do you read an env var?
lookup('env', 'NAME')
Did you understand? Let us try it once more.
Revision card
Interview card