Infrastructure as code · Intermediate · 20 min
Encrypt passwords and keys in your Ansible project with Ansible Vault
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · ansible-core 2.22.0
You will have an Ansible project whose passwords and tokens live encrypted in Git, with separate dev and prod vault passwords read from a private file and a password manager, secrets hidden from playbook output, and a rotated password.
On this page
An Ansible project sooner or later needs a database password, an API token or a private key. Leaving them in a plain vars file means everyone who can read the repository, every fork and every old clone has them. Ansible Vault encrypts those values with AES256 so the files can sit in Git next to the rest of the project, and ansible-playbook decrypts them in memory when it runs.
In this tutorial you build a small project that renders an application settings file for a dev and a prod environment. Both "servers" are your own machine, reached with Ansible's local connection, so you can focus on the vault. Everything works the same against real hosts over SSH. You will encrypt a whole vars file, encrypt one value inline, give each environment its own password, keep secrets out of the terminal output, and rotate a password.
Vault encryption runs on your machine and needs no network service or paid account, so it behaves the same on a laptop tethered to prepaid mobile data as on a build server. For the general habits around secrets in Git, see /tutorials/keep-secrets-out-of-git.
Step 1 · Install ansible-core and lay out the project
Install ansible-core 2.22.0 from PyPI with pipx, which gives it its own virtual environment. You only need the core package here: ansible-vault and the built-in modules are part of it.
sudo apt update
sudo apt install -y pipx
pipx install ansible-core==2.22.0
export PATH="$HOME/.local/bin:$PATH"
ansible --version | head -n 1
ansible-vault --version | head -n 1Add the PATH line to ~/.bashrc (or run pipx ensurepath) so the commands are found in new terminals. This install gets no updates from apt; upgrade it later with pipx upgrade ansible-core.
Now make a throwaway project folder with an inventory of two hosts, one per environment, and the plain (unencrypted) variables:
mkdir -p ~/vault-demo/group_vars/all ~/vault-demo/group_vars/dev ~/vault-demo/group_vars/prod
cd ~/vault-demo
cat > ansible.cfg <<'INI'
[defaults]
inventory = inventory.ini
INI
cat > inventory.ini <<'INI'
[dev]
app-dev ansible_connection=local
[prod]
app-prod ansible_connection=local
[all:vars]
ansible_python_interpreter="{{ ansible_playbook_python }}"
INI
cat > group_vars/all/vars.yml <<'YAML'
db_user: app
db_password: "{{ vault_db_password }}"
session_secret: "{{ vault_session_secret }}"
YAML
cat > group_vars/dev/vars.yml <<'YAML'
app_env: dev
db_host: db.dev.example.internal
YAML
ansible-inventory --graphansible_connection=local runs the tasks on this machine instead of over SSH, and the interpreter line tells Ansible to use the Python it is running on. In a real project these would be your dev and prod servers.
Look at group_vars/all/vars.yml. It names db_password and session_secret but holds no secret. Each points at a variable with a vault_ prefix that you will define in an encrypted file. This is the convention the Ansible docs recommend: a whole-file vault hides the variable names too, so the plain file is where people (and grep) find out which variables exist and where their real values come from.
Check it worked
The first two commands print ansible [core 2.22.0] and ansible-vault [core 2.22.0]. The graph shows @all with the groups @dev (containing app-dev) and @prod (containing app-prod).
Step 2 · Create an encrypted vars file
Create the encrypted file for the dev environment. --vault-id dev@prompt attaches the label dev to this file and asks you for its password; the label matters later, when prod gets a different password. Choose a long password and store it in your password manager now, because nothing can recover the file without it.
ansible-vault create --vault-id dev@prompt group_vars/dev/vault.ymlAnsible asks for the new password twice, then opens an editor. It uses $EDITOR, or vi if that is not set; run EDITOR=nano ansible-vault create ... to pick another. Type the secrets, with values of your own, then save and quit:
vault_db_password: replace-with-a-long-random-passwordWhen you save, Ansible encrypts the content and writes only ciphertext to disk. Look at the start of the file:
head -n 2 group_vars/dev/vault.yml
ls -l group_vars/dev/vault.ymlTo read it back, or change it, use view and edit. Both ask for the dev password. Add a second secret with edit:
ansible-vault view --vault-id dev@prompt group_vars/dev/vault.yml
ansible-vault edit --vault-id dev@prompt group_vars/dev/vault.ymlIn the editor, add a line under the first one and save:
vault_session_secret: replace-with-another-long-random-valueedit decrypts into a temporary file, runs the editor, and encrypts again when you quit. Avoid ansible-vault decrypt followed by a manual edit: it leaves the plain text on disk, and it is easy to commit it by accident.
Check it worked
The first line of the file is $ANSIBLE_VAULT;1.2;AES256;dev: format version 1.2 (the one with a label), the cipher, and the label. The rest is lines of hexadecimal. ls -l shows -rw-------, because ansible-vault creates files readable only by you. view prints both vault_ lines in plain text.
Step 3 · Use the secrets in a playbook
Write a template for the settings file and a playbook that renders it into a build/ folder, one file per host:
cat > app.env.j2 <<'J2'
APP_ENV={{ app_env }}
DB_HOST={{ db_host }}
DB_USER={{ db_user }}
DB_PASSWORD={{ db_password }}
SESSION_SECRET={{ session_secret }}
J2
cat > site.yml <<'YAML'
- name: Render the application settings
hosts: all
gather_facts: false
tasks:
- name: Make the output folder
ansible.builtin.file:
path: "{{ playbook_dir }}/build"
state: directory
mode: "0700"
- name: Write the settings file
ansible.builtin.template:
src: app.env.j2
dest: "{{ playbook_dir }}/build/{{ inventory_hostname }}.env"
mode: "0600"
YAMLNothing in the playbook mentions the vault. Ansible loads group_vars/dev/vault.yml like any other vars file and decrypts it in memory, as long as you give it the password. Run it for the dev host only, and type the dev password when asked:
ansible-playbook site.yml --limit dev --vault-id dev@promptWithout a password, the run fails with an error along the lines of Attempting to decrypt but no vault secrets found. That is the safe failure: Ansible never runs with a secret silently missing.
Check it worked
The recap shows app-dev with changed=2 failed=0. List the keys in the rendered file without printing the values:
ls -l build/
cut -d= -f1 build/app-dev.envbuild/app-dev.env is -rw-------, and the keys are APP_ENV, DB_HOST, DB_USER, DB_PASSWORD and SESSION_SECRET. Open the file and you will see the decrypted values. The build/ folder is output, so add it to .gitignore in a real project.
Step 4 · Read the password from a private file
Typing the password works for one-off runs, but not for a scheduled job or a long session. Ansible can read it from a file instead. Keep that file outside the project folder, so it can never be committed, and create it private before anything is written to it:
install -d -m 700 ~/.ansible-vault-demo
install -m 600 /dev/null ~/.ansible-vault-demo/dev.passNow put the dev password in it. read -s asks for it without echoing, so it never appears on screen, in your shell history or in the process list:
read -rsp 'Dev vault password: ' VAULT_PW; echo
printf '%s\n' "$VAULT_PW" > ~/.ansible-vault-demo/dev.pass
unset VAULT_PWPass the file in place of prompt. The quotes let the shell expand $HOME:
ansible-playbook site.yml --limit dev --vault-id "dev@$HOME/.ansible-vault-demo/dev.pass"Anyone who can read this file can decrypt the dev secrets, so treat it like a private SSH key: mode 600, never in the repository, never in a shared folder. On a CI system, store the password in the system's secret store and write it to a file at the start of the job.
Check it worked
ls -l ~/.ansible-vault-demo/dev.pass shows -rw-------. The playbook ran with no prompt, and the recap shows changed=0 failed=0 for app-dev, because the settings file already matches.
Step 5 · Keep secrets out of the output
Encryption protects the files at rest. It does nothing for what Ansible prints. Delete the rendered file and preview the run with check mode and --diff:
rm build/app-dev.env
ansible-playbook site.yml --limit dev --vault-id "dev@$HOME/.ansible-vault-demo/dev.pass" --check --diffThe diff prints the whole new file, but the two secret lines read DB_PASSWORD=$REDACTED$ and SESSION_SECRET=$REDACTED$. Since ansible-core 2.22, Ansible remembers every value it decrypts from a vault and masks that exact text in what it prints. It only knows the exact text, though. A value built from a secret, such as an encoded copy, is printed in full. Ask Ansible for the database password in base64, the form an HTTP Basic auth header uses:
ansible app-dev --vault-id "dev@$HOME/.ansible-vault-demo/dev.pass" -m ansible.builtin.debug -a 'msg={{ db_password | b64encode }}'The output shows the encoded password, and anyone can decode it with base64 -d. The same goes for secrets reformatted in a template, secrets that did not come from a vault, CI logs, -v output and any tool that collects Ansible's results. Two task keywords stop it at the source:
no_log: truereplaces the task's result with a "censored" message in every output and callback.diff: falseturns off the diff for that task, even when--diffis on.
Put both on every task that handles a secret. Rewrite the playbook with them on the template task:
cat > site.yml <<'YAML'
- name: Render the application settings
hosts: all
gather_facts: false
tasks:
- name: Make the output folder
ansible.builtin.file:
path: "{{ playbook_dir }}/build"
state: directory
mode: "0700"
- name: Write the settings file
ansible.builtin.template:
src: app.env.j2
dest: "{{ playbook_dir }}/build/{{ inventory_hostname }}.env"
mode: "0600"
no_log: true
diff: false
YAML
ansible-playbook site.yml --limit dev --vault-id "dev@$HOME/.ansible-vault-demo/dev.pass" --check --diff -v | tee /tmp/vault-demo-run.log | grep censoredThe cost of no_log is that a failing task tells you less. While debugging, set it from a variable (no_log: "{{ hide_secrets | default(true) }}") and turn it off with -e hide_secrets=false on a machine and log nobody else sees, then turn it back on.
Write the file for real again, and remove the log:
ansible-playbook site.yml --limit dev --vault-id "dev@$HOME/.ansible-vault-demo/dev.pass"
rm /tmp/vault-demo-run.logCheck it worked
The grep prints one line for app-dev containing "censored": "the output has been hidden due to the fact that 'no_log: true' was specified for this result", and no diff appears for the settings file. The last run recreated it: ls build/ lists app-dev.env again.
Step 6 · Encrypt a single value with encrypt_string
Sometimes you want one secret inside an otherwise readable file, for example an API token next to the plain dev settings. ansible-vault encrypt_string encrypts one value and prints it as YAML you can paste or append. With --stdin-name it reads the value from standard input and names the variable for you.
Read the token without echoing it:
read -rsp 'Dev API token: ' API_TOKEN; echoEncrypt it with the dev password and append it to the dev vars file. printf '%s' sends the value without a trailing newline, so the newline does not become part of the secret:
printf '%s' "$API_TOKEN" | ansible-vault encrypt_string --vault-id "dev@$HOME/.ansible-vault-demo/dev.pass" --stdin-name api_token >> group_vars/dev/vars.yml
unset API_TOKEN
cat group_vars/dev/vars.ymlHere the variable keeps its plain name, api_token, because the name stays visible in the file; only the value is encrypted. Add it to the template and render again:
cat > app.env.j2 <<'J2'
APP_ENV={{ app_env }}
DB_HOST={{ db_host }}
DB_USER={{ db_user }}
DB_PASSWORD={{ db_password }}
SESSION_SECRET={{ session_secret }}
API_TOKEN={{ api_token }}
J2
ansible-playbook site.yml --limit dev --vault-id "dev@$HOME/.ansible-vault-demo/dev.pass"Inline values are handy for one or two secrets, but they have a cost you will meet in the last step: rekey cannot change their password. Prefer a whole vault file when an environment has more than a couple of secrets.
Check it worked
group_vars/dev/vars.yml still shows app_env and db_host in plain text, followed by api_token: !vault | and an indented block that starts with $ANSIBLE_VAULT;1.2;AES256;dev. The playbook reports changed=1 for the settings file, and cut -d= -f1 build/app-dev.env now lists API_TOKEN as well.
Step 7 · Give prod its own password with vault IDs
Dev and prod should not share a password: people who need the dev secrets should not be able to read prod's. Vault IDs make this workable. Each file carries a label in its header, and you pass one --vault-id label@source per password.
For prod, keep the password in a password manager and have Ansible ask the manager for it. This tutorial uses pass, the standard Unix password manager, which stores each secret as a GPG-encrypted file. Install it and set it up with your GPG key as its documentation at passwordstore.org describes, then store a new prod vault password:
sudo apt install -y pass
pass insert ansible-vault/prodNow write a vault password client script. When a password source is an executable whose name ends in -client (with or without an extension), Ansible runs it as <script> --vault-id <label> and reads the password from its standard output. Exit code 2 tells Ansible the script has no password for that label. The script holds no secret, so it can live in the project and be committed:
cat > vault-pass-client.sh <<'SH'
#!/bin/sh
# Ansible runs this as: vault-pass-client.sh --vault-id <label>
# It prints that label's vault password from pass, and nothing else.
if [ "$1" != "--vault-id" ] || [ -z "$2" ]; then
echo "usage: $0 --vault-id <label>" >&2
exit 1
fi
secret=$(pass show "ansible-vault/$2") || exit 2
printf '%s\n' "$secret" | head -n 1
SH
chmod 755 vault-pass-client.sh
./vault-pass-client.sh --vault-id prod > /dev/null && echo "pass returned a prod password"If you use another password manager, change the pass show line to its command that prints one stored secret.
Write the plain prod settings, then create the prod vault file with the script as its password source. The editor opens as before; enter prod values of your own:
cat > group_vars/prod/vars.yml <<'YAML'
app_env: prod
db_host: db.prod.example.internal
YAMLansible-vault create --vault-id prod@./vault-pass-client.sh group_vars/prod/vault.ymlvault_db_password: replace-with-the-prod-database-password
vault_session_secret: replace-with-a-different-long-random-valueAdd the prod API token the same way as the dev one, encrypted with the prod ID:
read -rsp 'Prod API token: ' API_TOKEN; echoprintf '%s' "$API_TOKEN" | ansible-vault encrypt_string --vault-id prod@./vault-pass-client.sh --stdin-name api_token >> group_vars/prod/vars.yml
unset API_TOKENRun the playbook for both environments, with one --vault-id per password:
ansible-playbook site.yml --vault-id "dev@$HOME/.ansible-vault-demo/dev.pass" --vault-id prod@./vault-pass-client.sh
head -n 1 group_vars/dev/vault.yml group_vars/prod/vault.ymlBy default Ansible tries every password you give it on every encrypted value. To make it use only the password whose label matches, add vault_id_match = True under [defaults] in ansible.cfg. A person who is only given the dev password runs with --limit dev; without the prod password, a run that includes the prod host stops with a decryption error instead of using prod secrets.
Check it worked
The recap shows failed=0 for both app-dev and app-prod, and ls build/ lists app-dev.env and app-prod.env. The two headers end in ;dev and ;prod, so anyone can see which password a file needs without being able to read it.
Step 8 · Rotate a password with rekey
Change a vault password when someone with access leaves, or on a schedule. ansible-vault rekey decrypts a file with the old password and encrypts it with a new one. Rotate the dev password. First write the new password to a second private file:
install -m 600 /dev/null ~/.ansible-vault-demo/dev.pass.newread -rsp 'New dev vault password: ' VAULT_PW; echo
printf '%s\n' "$VAULT_PW" > ~/.ansible-vault-demo/dev.pass.new
unset VAULT_PWRekey the dev vault file from the old password to the new one:
ansible-vault rekey --vault-id "dev@$HOME/.ansible-vault-demo/dev.pass" --new-vault-id "dev@$HOME/.ansible-vault-demo/dev.pass.new" group_vars/dev/vault.ymlrekey only works on whole encrypted files. The inline api_token in group_vars/dev/vars.yml is still encrypted with the old password, and the Ansible docs are plain about it: you cannot rekey encrypted variables. Encrypt it again from its source, your password manager, with the new password. Rewrite the plain part of the file and append the new value:
read -rsp 'Dev API token: ' API_TOKEN; echocat > group_vars/dev/vars.yml <<'YAML'
app_env: dev
db_host: db.dev.example.internal
YAML
printf '%s' "$API_TOKEN" | ansible-vault encrypt_string --vault-id "dev@$HOME/.ansible-vault-demo/dev.pass.new" --stdin-name api_token >> group_vars/dev/vars.yml
unset API_TOKEN
mv ~/.ansible-vault-demo/dev.pass.new ~/.ansible-vault-demo/dev.passNow give the new password to everyone who should still have it, store it in your password manager in place of the old one, and update it in CI.
Rotating the vault password does not change the secrets inside. Anyone who had the old password and a copy of the old file, for example from Git history, can still read the old values. If a vault password has leaked, change the database password, the token and the session secret themselves, then update the vault files.
Check it worked
rekey prints Rekey successful. Run both environments with the rotated password file:
ansible-playbook site.yml --vault-id "dev@$HOME/.ansible-vault-demo/dev.pass" --vault-id prod@./vault-pass-client.shThe recap shows failed=0 for both hosts and changed=0, because the secrets themselves did not change. The old password no longer opens group_vars/dev/vault.yml.
Step 9 · Clean up
The next command deletes the demo project, including its vault files, and the demo password folder. Check that you have nothing of your own in ~/vault-demo or ~/.ansible-vault-demo before you run it:
cd ~
rm -rf ~/vault-demo ~/.ansible-vault-demoIf you stored a demo prod password in pass, remove it with pass rm ansible-vault/prod. If you installed ansible-core only for this tutorial, remove it with pipx uninstall ansible-core.
pass rm ansible-vault/prod
pipx uninstall ansible-coreCheck it worked
ls -d ~/vault-demo ~/.ansible-vault-demo 2>/dev/null || echo "demo folders removed"The command prints demo folders removed.
Next steps
- Split the playbook into roles, with secrets kept in group_vars: /tutorials/organise-ansible-work-into-roles
- Learn where group_vars, host_vars and other variable sources rank: /tutorials/organise-ansible-variables-with-group-vars-and-host-vars
- Keep secrets out of the rest of your repository too: /tutorials/keep-secrets-out-of-git
- Start from the basics of playbooks over SSH: /tutorials/configure-a-server-with-an-ansible-playbook
Related tutorials
- Write your first Pulumi program in TypeScriptYou will install the Pulumi CLI, keep state in a local folder, declare resources in a TypeScript program, preview and apply it, read its outputs, change it and watch the diff, then destroy and remove the stack.
- Set up a new cloud server on first boot with cloud-init user dataYou will write and validate one cloud-init file that gives a new Ubuntu 26.04 server a key-only sudo user, blocks root login, installs and upgrades packages, writes files with the right owners and runs setup commands once, ready to paste into any provider's user data field.
- Use Terraform workspaces for separate environments, and know when not toYou will run one Terraform configuration as separate dev and staging workspaces with per-environment settings, find where each workspace keeps its state, guard every apply with a workspace check, and compare the result with a directory per environment.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials