Since Lesson 3.4, the Aurora Store database has had a shortcoming that has been dragging along: the PostgreSQL users aurora and aurora_reporting have no password. The pg_hba.conf rules require scram-sha-256 from the web servers, so, in practice, the store wouldn't be able to connect to its database. In the previous lesson you generated two strong passwords, but you can't write them into the inventory as they are: the aurora-infra repository is read by every member of the team, and it's copied to laptops, to continuous integration servers and perhaps, one day, to a code hosting service. Ansible Vault solves this problem: it encrypts files or values with a master password, so that the repository only contains ciphertext and Ansible decrypts it in memory at run time. In this lesson you'll learn the ansible-vault commands, the ways of supplying the password (including vault IDs), the vault.yml + vars.yml pattern for organizing secrets in the inventory, and how to keep them from leaking through the output with no_log; and you'll finally give Aurora's PostgreSQL users a password.

Contents

  1. Why encrypt secrets
  2. What Ansible Vault is
  3. First steps: create, view and edit
  4. Encrypting, decrypting and changing the password: encrypt, decrypt and rekey
  5. Encrypting a single value: encrypt_string
  6. How Ansible receives the Vault password
  7. Vault IDs: labeled passwords
  8. Practice: Aurora's Vault password
  9. The vault.yml + vars.yml pattern
  10. Practice: Aurora's secrets in the inventory
  11. Practice: passwords in the postgresql and aurora_app roles
  12. no_log and other secret leaks
  13. Verifying and saving the work
  14. Best practices and security warnings

  1. Why encrypt secrets

A plain-text secret inside a repository leaks in many ways:

Leak path Example
Git history Even if you delete the line, it's still in every previous commit and in every copy of the repository
Copies of the repository Laptops, backups, CI servers, forks
Code review A diff with the password visible in a web tool
Ansible output --diff, -v or a debug that prints the variable
Screenshots and logs A screenshot in a ticket, a public CI log

Vault protects the first three paths: what gets stored and shared is ciphertext. The last two depend on how you write your playbooks (section 12).

  1. What Ansible Vault is

Ansible Vault is a feature included in Ansible (you don't need to install anything) that:

  • Encrypts entire files or individual values with AES-256, using a key derived from a Vault password.
  • Is managed with the ansible-vault command.
  • Is transparent to playbooks: if a variables file is encrypted, Ansible decrypts it in memory when it loads it, as long as it has the password. Tasks and templates use the variables like any others.

An encrypted file looks like this:

$ANSIBLE_VAULT;1.1;AES256
62313365396662343061393464336163383764373764613633653634306231386433626436623361
6630386233653631326134663232343332633465326333310a376630613235316438393737326632
...

The first line is the header: the Vault format (1.1, or 1.2 when it has a label, section 7) and the algorithm. The rest is the encrypted content, encoded in hexadecimal. Without the password, nothing can be read, not even the variable names.

  1. First steps: create, view and edit

Practice first with a throwaway file, in ~/aurora-infra:

ansible-vault create demo-secret.yml
New Vault password:
Confirm New Vault password:

Ansible asks for a password (type a test one, for example test-vault) and opens your editor (the one in the EDITOR environment variable; if it isn't defined, vi). Write:

---
demo_key: test-secret-value

Save and close. The file on disk is encrypted:

cat demo-secret.yml
$ANSIBLE_VAULT;1.1;AES256
3864353563386461...

To read it without modifying it, or to edit it:

ansible-vault view demo-secret.yml
ansible-vault edit demo-secret.yml

edit decrypts the content into a temporary file, opens the editor and, when you close it, encrypts it again and deletes the temporary file. It's the right way to modify an encrypted file: never decrypt it "for a moment" inside the repository itself.

If you want to use a different editor just for Vault: EDITOR=nano ansible-vault edit demo-secret.yml.

  1. Encrypting, decrypting and changing the password: encrypt, decrypt and rekey

Command What it does Example
create Creates a new encrypted file and opens the editor ansible-vault create vault.yml
view Shows the decrypted content ansible-vault view vault.yml
edit Edits the content and encrypts it again ansible-vault edit vault.yml
encrypt Encrypts an existing plain-text file ansible-vault encrypt vault.yml
decrypt Decrypts a file and leaves it in plain text on disk ansible-vault decrypt vault.yml
rekey Changes the password of one or more encrypted files ansible-vault rekey vault.yml
encrypt_string Encrypts a single value to paste into a YAML file ansible-vault encrypt_string --name x

Try decrypt and encrypt with the test file:

ansible-vault decrypt demo-secret.yml    # asks for the password; it's left in plain text
cat demo-secret.yml
ansible-vault encrypt demo-secret.yml    # asks for a new password; encrypts it again

Be careful with decrypt: it leaves the secret in plain text on disk, and a careless git add . would take it into the repository. To read, use view; to modify, edit.

rekey changes the password without touching the content:

ansible-vault rekey demo-secret.yml
Vault password:
New Vault password:
Confirm New Vault password:
Rekey successful

You can pass it several files at once; they must all have the same current password.

  1. Encrypting a single value: encrypt_string

Sometimes you don't want to encrypt a whole file, but rather one value inside a file that is otherwise readable:

ansible-vault encrypt_string --name demo_token 'test-secret-value'
New Vault password:
Confirm New Vault password:
Encryption successful
demo_token: !vault |
          $ANSIBLE_VAULT;1.1;AES256
          65306436323264356530643966653634343839386562303736616531393430353163663466333434
          ...

The output is YAML ready to paste into a variables file. The !vault tag tells Ansible that that particular value is encrypted.

Be careful about typing the secret on the command line: it stays in your shell history. It's better to have it read from standard input:

ansible-vault encrypt_string --stdin-name demo_token

Type the value, press Enter and then Ctrl+D (without an additional newline, or it will become part of the secret).

Encrypted file or encrypted values? Both approaches are valid:

Aspect Whole file encrypted Values with encrypt_string
Readability of the file None without the password Names and the rest of the values are visible
Editing a secret ansible-vault edit Generate the value again and paste it
Changing the password (rekey) Straightforward rekey doesn't work with individual values: you have to re-encrypt them one by one
Diff in git The whole encrypted block Only the affected value changes

Aurora uses whole encrypted files with the pattern from section 9, which keeps the best of both worlds: the variable names remain visible in an unencrypted file.

Delete the test file:

rm demo-secret.yml

  1. How Ansible receives the Vault password

When it runs a playbook that loads encrypted files, Ansible needs the password. If it doesn't have it, it fails:

ERROR! Attempting to decrypt but no vault secrets found

There are several ways to give it the password:

Form Example Typical use
Ask for it interactively ansible-playbook site.yml --ask-vault-pass (or -J) One-off manual runs
Password file on the command line ansible-playbook site.yml --vault-password-file ~/.ansible/vault/aurora-lab.pass Automation
Password file in ansible.cfg vault_password_file = ~/.ansible/vault/aurora-lab.pass in [defaults] Project with a single password
Environment variable ANSIBLE_VAULT_PASSWORD_FILE=~/.ansible/vault/aurora-lab.pass CI/CD (Lesson 8.3)
Vault ID --vault-id lab@prompt or vault_identity_list in ansible.cfg Several labeled passwords (section 7)

The password file contains only the password, on the first line. If the file is executable, Ansible doesn't read it: it runs it and uses whatever it prints. That way you can get the password from a password manager or the system keyring instead of storing it in a file (for example, a small script that calls pass show aurora/vault-lab).

Rules for the password file:

  • Outside the repository. Always. If it's inside, encryption is pointless.
  • Permissions 0600 (only your user can read it).
  • A copy of the password in the team's password manager: if it's lost, the encrypted secrets are unrecoverable.

  1. Vault IDs: labeled passwords

A real project usually has several Vault passwords: one for the lab and staging, another for production, which fewer people know. Vault IDs associate each password with a label:

ansible-vault create --vault-id lab@prompt secret.yml

The label@source form accepts as its source:

Source Meaning
prompt Ask for the password at the keyboard
A path A file (or script) with the password

When you encrypt with a vault ID, the label is stored in the header, which moves to version 1.2:

$ANSIBLE_VAULT;1.2;AES256;lab

At run time, you can supply several identities at once:

ansible-playbook site.yml --vault-id lab@~/.ansible/vault/aurora-lab.pass --vault-id prod@prompt

Ansible uses the label in the header to try the right password first (and, if it doesn't match, it tries the others). In ansible.cfg, the equivalent option is vault_identity_list, a comma-separated list.

Today Aurora has only one environment, the lab (aurora_env: lab), so it will use a single identity, lab. Labeling it from the start has an advantage: when staging and production appear in Lesson 9.1, each environment will have its own label and its own password without having to re-encrypt anything you do today.

  1. Practice: Aurora's Vault password

Create the directory and the password file outside the repository, with a random password:

mkdir -p ~/.ansible/vault
chmod 700 ~/.ansible/vault
ansible localhost -m ansible.builtin.copy \
  -a "dest={{ '~/.ansible/vault/aurora-lab.pass' | expanduser }} mode=0600 content={{ lookup('ansible.builtin.password', '/dev/null', length=32, chars=['ascii_letters', 'digits']) }}"
ls -l ~/.ansible/vault/aurora-lab.pass
-rw------- 1 student student 32 Nov 26 10:20 /home/student/.ansible/vault/aurora-lab.pass

You've reused the password lookup from Lesson 5.3 to generate 32 random characters, and the copy module on localhost to create the file with 0600 permissions from the very first moment. (You can do the same with openssl rand -base64 32 > file && chmod 600 file, or with your password manager.) Keep a copy of this password in the team's password manager.

Configure the identity in ansible.cfg, in [defaults]:

# Lab Vault password (label "lab"). The file is OUTSIDE the
# repository and is never versioned.
vault_identity_list = lab@~/.ansible/vault/aurora-lab.pass

From now on, ansible-vault and ansible-playbook will use that identity without asking: ansible-vault create will encrypt with the lab label and ansible-playbook will decrypt the files without prompting for anything. When several identities are configured, you'll have to specify which one to encrypt with (--encrypt-vault-id, or vault_encrypt_identity in ansible.cfg).

As an extra defense, add patterns to the project's .gitignore that prevent password files from being versioned even if someone copies them into the repository by mistake:

# Vault passwords: never in the repository
*.pass
.vault_pass*

  1. The vault.yml + vars.yml pattern

If you encrypt the whole of inventory/group_vars/dbservers.yml, you lose the ability to read all its variables (version, port, users…), even though only one is secret. And a grep postgresql_users in the repository would no longer find where it's defined. The recommended pattern splits the data into two files inside a group_vars directory:

inventory/group_vars/dbservers/
├── vars.yml      ← plain text: all the variables, including the secret ones (by reference)
└── vault.yml     ← encrypted: only the secret values, with the vault_ prefix
# vars.yml (plain text)
postgresql_users:
  - name: aurora_reporting
    password: "{{ vault_aurora_reporting_db_password }}"
# vault.yml (encrypted)
vault_aurora_reporting_db_password: 9hT2kLm...

The rules of the pattern:

  • Each secret is stored in vault.yml with the vault_ prefix.
  • The normal variables (vars.yml or any other plain-text file) reference it.
  • That way, grep -r aurora_reporting_db_password inventory/ finds where it's used, and anyone reading vars.yml knows a secret exists even if they can't see it.

Ansible loads all the files in a group_vars (or host_vars) directory in alphabetical order, as if they were a single file. You've been using this since Module 2 with group_vars/all/ (aurora.yml, common.yml, team.yml). The names vars.yml and vault.yml are a convention, not a requirement. What you shouldn't do is have both group_vars/dbservers.yml and group_vars/dbservers/ at the same time: it's confusing to know where each value comes from.

  1. Practice: Aurora's secrets in the inventory

Aurora has two secrets, which live in different places depending on who needs them:

Secret Needed by Where it's stored
Password of the aurora user db1 (to create the user) and web1/web2 (to connect) group_vars/all/vault.yml
Password of the aurora_reporting user Only db1 group_vars/dbservers/vault.yml

10.1. The shared secret: group_vars/all/

ansible-vault create inventory/group_vars/all/vault.yml

Write (with the password you generated in Lesson 5.3; the example value is fictitious):

---
# Aurora Store secrets shared by several groups. Encrypted with Vault (id: lab).
vault_aurora_db_password: q7RkV2mX9tPzL4cWb8NfH3sY

Check the header:

head -1 inventory/group_vars/all/vault.yml
$ANSIBLE_VAULT;1.2;AES256;lab

And in inventory/group_vars/all/aurora.yml, add the reference:

# Password of the store's database user (secret in vault.yml).
aurora_db_password: "{{ vault_aurora_db_password }}"

10.2. The database secrets: group_vars/dbservers/

Turn the group file into a directory. Use git mv so that git keeps the file's history:

mkdir inventory/group_vars/dbservers
git mv inventory/group_vars/dbservers.yml inventory/group_vars/dbservers/vars.yml
ansible-vault create inventory/group_vars/dbservers/vault.yml

Content of vault.yml (again, with your real password):

---
# Secrets of the Aurora Store database servers. Encrypted with Vault (id: lab).
vault_aurora_reporting_db_password: 9hT2kLmQ4xVb7NcRz3WpY8sD

In inventory/group_vars/dbservers/vars.yml, add the password to each user in postgresql_users:

postgresql_users:
  - name: "{{ aurora_db_user }}"
    password: "{{ aurora_db_password }}"
  - name: aurora_reporting
    password: "{{ vault_aurora_reporting_db_password }}"

The store user uses aurora_db_password (the "normal" variable, defined in all), and the reporting user references its secret directly: both styles follow the pattern, because the value only exists in vault.yml.

10.3. The password for the website: group_vars/webservers.yml

Next to the other aurora_app connection parameters:

aurora_app_db_password: "{{ aurora_db_password }}"

Check that the variables resolve without printing the secrets (count the vault_ variables and show only the user names):

ansible-inventory --host db1 | grep -c vault_
ansible db1 -m ansible.builtin.debug -a "msg={{ postgresql_users | map(attribute='name') | list }}"

The first command should count at least 2 lines: ansible-inventory --host db1 shows the host's variables already decrypted, including vault_aurora_db_password and vault_aurora_reporting_db_password with their values; that's why you filter it with grep -c instead of looking at all of it. Keep this in mind: anyone with the Vault password can see all the secrets, and the output of this command must not be shared.

  1. Practice: passwords in the postgresql and aurora_app roles

11.1. The postgresql role

roles/postgresql/tasks/users.yml, first task:

- name: Create the PostgreSQL users
  community.postgresql.postgresql_user:
    name: "{{ item.name }}"
    password: "{{ item.password | default(omit) }}"
    port: "{{ postgresql_port }}"
    state: present
  become_user: postgres
  loop: "{{ postgresql_users }}"
  loop_control:
    label: "{{ item.name }}"
  no_log: true
  • password: "{{ item.password | default(omit) }}": users without a password keep working as before (the role is generic).
  • PostgreSQL 16 stores the password with scram-sha-256, the same method that pg_hba.conf requires. Ansible sends the value in plain text over the local connection and the server stores only its derived form.
  • no_log: true: explained in section 12. label isn't enough.

Update the specification (roles/postgresql/meta/argument_specs.yml) by adding the suboption to postgresql_users:

        options:
          name:
            type: str
            required: true
            description: User name.
          password:
            type: str
            description: User password. Store it encrypted with Ansible Vault.

And in roles/postgresql/README.md, replace the note "User passwords aren't managed yet" with one saying that the password is passed in password and must come from Vault.

11.2. The aurora_app role

The application needs the password in /etc/aurora/db.conf. It has no reasonable default value, so it's mandatory, like aurora_app_db_host. Add it to roles/aurora_app/meta/argument_specs.yml:

      aurora_app_db_password:
        type: str
        required: true
        description: Password of the database user. It must come encrypted with Ansible Vault.

In roles/aurora_app/templates/db.conf.j2, one more line after the user:

AURORA_DB_USER={{ aurora_app_db_user }}
AURORA_DB_PASSWORD={{ aurora_app_db_password }}
AURORA_DB_DSN={{ aurora_app_db_dsn }}

The AURORA_DB_DSN string does not include the password: if a log or an error message ever showed the connection string, it wouldn't expose it.

And the task, in roles/aurora_app/tasks/main.yml:

- name: Publish the database connection details
  ansible.builtin.template:
    src: db.conf.j2
    dest: "{{ aurora_app_config_dir }}/db.conf"
    owner: root
    group: "{{ aurora_app_owner }}"
    mode: "0640"
  diff: false

Three changes compared to before:

  • mode: "0640" and group: "{{ aurora_app_owner }}": the file contains a secret, so not just any user on the server can read it anymore; only root and the application's group (deploy).
  • diff: false: with --diff, Ansible would show the old and new content of the file, password included. This keyword disables the diff for this task only.

11.3. Checking that the store can authenticate

Until now, dbservers.yml checked that PostgreSQL accepts connections as postgres. Add a check that uses the store's credentials, in post_tasks, after the existing one:

    - name: Check that the store can authenticate to its database
      community.postgresql.postgresql_ping:
        login_host: 127.0.0.1
        login_user: "{{ aurora_db_user }}"
        login_password: "{{ aurora_db_password }}"
        db: "{{ aurora_db_name }}"
        port: "{{ postgresql_port }}"
      register: aurora_db_ping
      failed_when: not aurora_db_ping.is_available
  • It connects over TCP to 127.0.0.1, which in pg_hba.conf requires scram-sha-256: if the password weren't correct, it would fail.
  • postgresql_ping reports the result in is_available; depending on the collection version, it may not fail by itself when it can't connect. failed_when makes the criterion explicit (you'll study it in depth in Lesson 5.5).
  • login_password is a parameter marked as secret in the module itself: Ansible hides it in the output, even if you use -vvv.

  1. no_log and other secret leaks

Encrypting the inventory doesn't stop a secret from appearing in Ansible's output. Look at what the users task would show without no_log when run with -v:

changed: [db1] => (item=aurora) =>
    ansible_loop_var: item
    changed: true
    item:
        name: aurora
        password: q7RkV2mX9tPzL4cWb8NfH3sY
    ...

loop_control.label only changes the text in parentheses (item=aurora); the detailed result still includes the whole element. With no_log: true, Ansible censors the task's entire result:

TASK [postgresql : Create the PostgreSQL users] ********************************
changed: [db1] => (item=None)
changed: [db1] => (item=None)

Even with -vvv you'll see "censored": "the output has been hidden due to the fact that 'no_log: true' was specified for this result". The price is that, if the task fails, you won't see the reason either. To debug, remove no_log temporarily in the lab, never against production.

Places where secrets slip out and how to close them:

Leak Protection
The result of a task with the secret in its parameters or in item no_log: true
--diff of a file that contains the secret diff: false on the task
A debug with the variable Don't do it; if it's essential, only in the lab
Files on the server with broad permissions Restrictive mode (0600/0640) and the right owner
Control node logs (log_path in ansible.cfg) Review what gets logged; no_log also protects the log
Vault password files in the repository Outside the repository + .gitignore

Note the last row of the previous table: well-written modules mark their secret parameters (like login_password or the password of postgresql_user), and Ansible hides them automatically. But a secret can travel along other paths, such as the item of a loop or the content of a template, which the module knows nothing about.

  1. Verifying and saving the work

Apply the infrastructure (you no longer need to supply the password: it's taken from vault_identity_list):

ansible-playbook site.yml
TASK [postgresql : Create the PostgreSQL users] ********************************
changed: [db1] => (item=None)
changed: [db1] => (item=None)
...
TASK [aurora_app : Publish the database connection details] ********************
changed: [web1]
changed: [web2]
...
TASK [Check that the store can authenticate to its database] *******************
ok: [db1]
...
PLAY RECAP *********************************************************************
db1                        : ok=...  changed=1    unreachable=0    failed=0    ...
web1                       : ok=...  changed=1    unreachable=0    failed=0    ...
web2                       : ok=...  changed=1    unreachable=0    failed=0    ...

A second run should give changed=0. Current versions of community.postgresql compare the password with the stored scram-sha-256 value; if in your version the users task comes out changed on every run, update the collection or add update_password: on_create to the task (it would only set the password when creating the user, and then changing it would require another procedure).

Check the permissions of the store's file:

ansible webservers -b -m ansible.builtin.command -a "stat -c '%U:%G %a' /etc/aurora/db.conf"
web1 | CHANGED | rc=0 >>
root:deploy 640
web2 | CHANGED | rc=0 >>
root:deploy 640

Also try what happens without the Vault password, so you'll recognize the error:

ANSIBLE_VAULT_IDENTITY_LIST= ansible-playbook site.yml --check
ERROR! Attempting to decrypt but no vault secrets found

Before committing, check that the vault.yml files are encrypted and that there's nothing in plain text that shouldn't be:

head -1 inventory/group_vars/all/vault.yml inventory/group_vars/dbservers/vault.yml
git status
git add .gitignore ansible.cfg inventory/ roles/ dbservers.yml
git commit -m "PostgreSQL passwords encrypted with Ansible Vault (id lab)"

A useful trick for reviewing changes in encrypted files: git can show their decrypted diff if you tell it to. In the repository's .gitattributes:

*vault.yml diff=ansible-vault

And, in your local git configuration (not in the repository):

git config diff.ansible-vault.textconv "ansible-vault view"

With that, git diff and git log -p show the decrypted content of the vault.yml files in your terminal, while the repository keeps storing only ciphertext.

  1. Best practices and security warnings

Practice Reason
Vault password outside the repository, with 0600 permissions, and a copy in a password manager If it's lost, the secrets are unrecoverable; if it leaks, they're all exposed
The vault.yml + vars.yml pattern with the vault_ prefix The variable names remain visible and searchable
One vault ID per environment (lab, staging, production) Whoever works in the lab doesn't need the production password
no_log: true on tasks that handle secrets in loops or results The output and the logs don't show them
diff: false on templates with secrets --diff doesn't print them
Files with secrets on the servers with minimal permissions Encryption protects the repository, not the server
Never decrypt in the repository A careless git add would publish the secret
Rotate secrets, not just the Vault password See the following warning

An important warning about rekey: if the Vault password leaks, changing it with rekey isn't enough. The previous versions of the files, encrypted with the old password, are still in the git history and in every copy of the repository. The right thing to do is to change the secrets themselves (the PostgreSQL passwords, in Aurora) and encrypt them with a new Vault password.

And a reminder about scope: Vault protects secrets at rest inside the repository. It isn't a full secrets manager: it doesn't rotate passwords, record who accesses them or expire them. Large organizations usually combine Ansible with an external manager (HashiCorp Vault, AWS Secrets Manager, Azure Key Vault…) through lookups from their collections, and AWX stores the Vault password as just another credential (Lesson 7.5). Lesson 9.2 revisits the security of the project as a whole. As with everything related to security, in a real environment it's a good idea to have a security professional review the design.

Common Mistakes and Tips

  • ERROR! Attempting to decrypt but no vault secrets found: Ansible doesn't have any password. Check vault_identity_list in ansible.cfg, the path of the file, and that you're running from ~/aurora-infra.
  • ERROR! Decryption failed (no vault secrets were found that could decrypt): it has a password, but it isn't the right one for that file (for example, you encrypted it with --ask-vault-pass and a different password).
  • 'vault_aurora_db_password' is undefined: the vault.yml file isn't where Ansible looks for it (did you create it in the inventory's group_vars/all/?) or the variable name doesn't match.
  • An extra newline in the secret: when using encrypt_string --stdin-name, pressing Enter before Ctrl+D adds \n to the value.
  • Passwords visible with -v: label isn't enough in loops; use no_log: true.
  • Editing the encrypted file with a normal editor: you'd corrupt it. Always use ansible-vault edit.
  • Tip: every now and then, look for plain-text secrets in the repository with git grep -i -e password -e secret -e token and check that every match is a reference to a vault_ variable. In Lesson 9.4 you'll see tools that automate this.

Exercises

Exercise 1: Changing the Vault password

Generate a new Vault password in ~/.ansible/vault/aurora-lab-new.pass and re-encrypt the two vault.yml files with it, keeping the lab label. Then make ansible.cfg use the new file and check that ansible-playbook site.yml --check works.

Exercise 2: A standalone encrypted value

Use encrypt_string (reading from standard input) to encrypt a fictitious value called vault_demo_api_token and paste it into a test file demo-vars.yml. Write a minimal playbook against localhost that uses vars_files: [demo-vars.yml] and shows the length of the value (not the value). Delete both files when you're done.

Exercise 3: Security review

A colleague proposes adding this task to aurora_app to make debugging easier. Point out all the problems:

- name: Show the database configuration
  ansible.builtin.debug:
    msg: "Connecting to {{ aurora_app_db_dsn }} with the password {{ aurora_app_db_password }}"

Solutions

Exercise 1.

ansible localhost -m ansible.builtin.copy \
  -a "dest={{ '~/.ansible/vault/aurora-lab-new.pass' | expanduser }} mode=0600 content={{ lookup('ansible.builtin.password', '/dev/null', length=32, chars=['ascii_letters', 'digits']) }}"
ansible-vault rekey --new-vault-id lab@~/.ansible/vault/aurora-lab-new.pass \
  inventory/group_vars/all/vault.yml inventory/group_vars/dbservers/vault.yml

The current password is taken from vault_identity_list; the new one, from --new-vault-id. Then change the path in ansible.cfg to aurora-lab-new.pass, check with ansible-playbook site.yml --check and, when everything works, delete the old file and update the copy in the password manager. Remember that this does not protect the secrets if the old password had leaked (section 14). If you'd rather keep the name aurora-lab.pass, rename the new file at the end and leave ansible.cfg as it was.

Exercise 2.

ansible-vault encrypt_string --stdin-name vault_demo_api_token > demo-vars.yml
# type a fictitious value and press Ctrl+D (without Enter)
---
# demo-vault.yml (for testing only)
- name: Use an encrypted value
  hosts: localhost
  gather_facts: false
  vars_files:
    - demo-vars.yml
  tasks:
    - name: Show the length of the token
      ansible.builtin.debug:
        msg: "The token has {{ vault_demo_api_token | length }} characters"
ansible-playbook demo-vault.yml
rm demo-vault.yml demo-vars.yml

encrypt_string uses the lab identity from ansible.cfg, so the playbook decrypts it without asking for anything. The Encryption successful line that encrypt_string prints goes to standard error, not to demo-vars.yml.

Exercise 3. Problems: (1) it prints the password in the output of every run, and with it in the CI, AWX or log_path logs; (2) it also prints it in --check mode; (3) adding no_log: true to it would make the task useless (it wouldn't show anything); (4) the useful information (server, port, database) is already in aurora_app_db_dsn, which doesn't contain the password. Alternative: show only the DSN and, at most, aurora_app_db_password | length > 0 to know there's a password, preferably with verbosity: 1 so that it only appears with -v.

Conclusion

Aurora Store's secrets are no longer either in plain text or missing: the passwords of the aurora and aurora_reporting users live encrypted with Ansible Vault in inventory/group_vars/all/vault.yml and inventory/group_vars/dbservers/vault.yml, referenced from normal variables (aurora_db_password, postgresql_users, aurora_app_db_password) following the vault.yml + vars.yml pattern. You know the create, view, edit, encrypt, decrypt, rekey and encrypt_string commands, the ways of supplying the password (--ask-vault-pass, --vault-password-file, vault_password_file) and vault IDs, with which Aurora uses the lab identity configured in vault_identity_list and a password file outside the repository. You've also protected the output with no_log and diff: false, restricted the permissions of /etc/aurora/db.conf and added a real authentication check to dbservers.yml. With real passwords, a failing configuration is no longer a theoretical problem: a deployment can break the website or leave a server half-configured. In the next lesson, Error Handling, you'll learn how Ansible reacts to failures and how to control that with failed_when, ignore_errors, block/rescue/always and checks with assert, and you'll make the Aurora website deployment roll back automatically if the new version doesn't work.

Ansible Course: From Beginner to Advanced

Module 1: Introduction to Ansible

Module 2: Ansible Fundamentals

Module 3: Playbooks

Module 4: Roles

Module 5: Advanced Playbook Techniques

Module 6: Ansible Galaxy

Module 7: Ansible Tower, AWX and Automation Platform

Module 8: Ansible for DevOps

Module 9: Ansible Best Practices

Module 10: Advanced Ansible Topics

Module 11: Final Project

© Copyright 2026. All rights reserved