Skip to main content
Ansible Configuration
CHAPTER 15

Ansible Vault and Security Best Practices

Updated: May 15, 2026
25 min read

# CHAPTER 15

Ansible Vault and Security Best Practices

1. Introduction

We have established that your Ansible code must live in a Git repository to enable CI/CD pipelines. But this introduces a massive security dilemma. Your playbooks configure databases, applications, and APIs, all of which require passwords, private keys, and tokens. If you hardcode a database password into vars/main.yml, you have just committed a plain text password to version control. Anyone with read access to the repository—or a hacker who breaches it—instantly owns your database. In this chapter, we solve this critical vulnerability by introducing Ansible Vault, the native cryptographic tool that encrypts sensitive data so it can be safely stored alongside your code.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Identify the security risks of hardcoding credentials in version control.
  • Use the ansible-vault CLI to create, encrypt, edit, and decrypt files.
  • Encrypt specific string variables within a plaintext YAML file.
  • Execute playbooks that require Vault passwords (--ask-vault-pass).
  • Securely integrate Ansible Vault passwords into CI/CD pipelines.

3. Beginner-Friendly Explanation

Imagine sending a diary in the mail.
  • The Vulnerability: You write your deepest secrets in the diary and put it in the mailbox. The postman, the mail sorter, and anyone who intercepts it can read your secrets.
  • Ansible Vault: You buy a diary with a heavy padlock on it. You lock your secrets inside. You can safely put the locked diary in the mail, store it in a public library (GitHub), or leave it on a park bench. Unless someone possesses the physical key to unlock the padlock, the diary looks like total gibberish.

Ansible Vault mathematically encrypts your variables so they are safe to store anywhere.

4. Encrypting Files with Ansible Vault

Ansible Vault uses AES-256 encryption. Let's secure a file containing our database password.

Step 1: Creating an encrypted file

bash
1
ansible-vault create secrets.yml

You will be prompted to create a "Vault Password". Do not lose this password. A text editor will open. Type your secret variables:

yaml
12
db_password: "SuperSecretPassword123!"
api_token: "xyz987"

Save and close the file.

Step 2: Viewing the encryption If you run cat secrets.yml in your terminal, you will not see your password. You will see this:

text
123
$ANSIBLE_VAULT;1.1;AES256
65346330613262333036666138623631623835613337353965313939613134383161356461323332
3438363737396637313063373836366632346132383838330a386134373130623266393563346536

*This file is now 100% safe to commit to GitHub.*

Step 3: Editing the file To change the password later, you cannot use a normal text editor. You must use Vault:

bash
1
ansible-vault edit secrets.yml

5. Running Playbooks with Vaulted Secrets

If your playbook references the db_password variable located inside secrets.yml, you must provide the master key when you execute the playbook. Otherwise, Ansible cannot decrypt the file and will crash.
bash
12
# The --ask-vault-pass flag prompts you to type the master password
ansible-playbook site.yml --ask-vault-pass

6. Mini Project: Automate Vault Passwords for CI/CD

Prompting a human to type a password (--ask-vault-pass) completely breaks CI/CD automation. A robot cannot type a password. We must pass the vault key automatically via a file.

Step-by-Step Architecture Concept:

  1. 1. Save your master Vault password in a text file. Let's pretend it's saved at ~/.vault_pass.txt.
  1. 2. Ensure this file has strict permissions (chmod 600) and is NEVER committed to Git.
  1. 3. Run the playbook, pointing to the password file:

bash
1
ansible-playbook site.yml --vault-password-file ~/.vault_pass.txt

In a CI/CD Pipeline (GitHub Actions): You store the master Vault password as a GitHub Secret.

yaml
12345678910
      - name: Run Ansible Playbook
        run: |
          # Write the secret to a temporary file
          echo "${{ secrets.ANSIBLE_VAULT_PASSWORD }}" > .vault_pass
          
          # Run the playbook using the temporary file
          ansible-playbook site.yml --vault-password-file .vault_pass
          
          # Delete the file immediately for security
          rm .vault_pass

7. Real-World Scenarios

A junior developer was configuring a corporate Slack bot. They pasted the Slack API token directly into their roles/slack/vars/main.yml file and pushed it to a public GitHub repository. Within 10 minutes, a hacker scraped GitHub, found the token, and used the bot to send spam messages to the entire company. The CISO mandated the use of Ansible Vault. The DevOps team ran ansible-vault encryptstring 'myslacktoken' --name 'slackapitoken' to encrypt only that specific line of text. The playbook was safely pushed back to GitHub containing only AES-256 encrypted gibberish, permanently securing the infrastructure.

8. Best Practices

  • Separate Secrets from Configs: Do not encrypt your entire vars/main.yml file if it contains 50 harmless variables (like httpport: 80) and 1 secret password. Encrypting the whole file makes it impossible to review code changes in Git (because Git just sees encrypted gibberish changing). Always split your variables: put harmless variables in vars.yml and passwords in secrets.yml, and only encrypt secrets.yml.

9. Security Recommendations

  • Multiple Vault Passwords: In enterprise environments, you don't want the developers who have the "Dev" vault password to be able to decrypt the "Production" vault files. Ansible allows you to use Multiple Vault Passwords. You can encrypt devsecrets.yml with one key, and prodsecrets.yml with a completely different, highly restricted key.

10. Troubleshooting Tips

  • Decryption Failed: If Ansible throws an ERROR! Decryption failed message, it means you either typed the vault password incorrectly, or you used the wrong --vault-password-file. Ansible will not tell you *which* file failed to decrypt, so ensure your password files are meticulously organized.

11. Exercises

  1. 1. What CLI command is used to safely modify the contents of an existing encrypted vault file?
  1. 2. Explain the security flaw of running ansible-vault decrypt on a file before committing it to a version control system.

12. FAQs

Q: Can I integrate Ansible with third-party secret managers like HashiCorp Vault or AWS Secrets Manager? A: Yes! This is the ultimate enterprise standard. Instead of using Ansible Vault files, you use specialized lookup plugins in your playbook (e.g., lookup('awssecret', 'mydb_password')) to fetch the password dynamically from the secure API at runtime.

13. Interview Questions

  • Q: Describe the operational risks of committing unencrypted variables to a Git repository. How does Ansible Vault mitigate this risk while maintaining a GitOps workflow?
  • Q: You need to execute an Ansible Playbook containing Vault-encrypted variables via an automated Jenkins pipeline. Detail the mechanism for providing the decryption key without requiring interactive human input.

14. Summary

In Chapter 15, we secured the final vulnerability in our Infrastructure as Code pipeline. We recognized that while Git is the perfect vessel for sharing code, it is a catastrophic vessel for sharing credentials. By implementing Ansible Vault, we applied AES-256 encryption to our sensitive variables, transforming plain text passwords into secure, version-controllable ciphertext. We mastered the lifecycle of creating, editing, and decrypting vaults, and engineered a CI/CD-friendly workflow utilizing password files to ensure our automated pipelines remain both independent and impregnable.

15. Next Chapter Recommendation

Our automation is fast, secure, and running in the cloud. But what happens when it breaks in the middle of the night? Proceed to Chapter 16: Monitoring and Troubleshooting Ansible.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·