← Recipes

阅读中文版本

Encrypt Secrets in Ansible with Vault

Encrypt variable files with ansible-vault, reference the vault password from a secure source, and structure variables so secrets stay out of plaintext inventory.

~35 minansiblesecretsautomation

Task

Manage Ansible secrets with vault-encrypted variable files instead of plaintext.

When to use this

Passwords sit in plaintext group_vars committed to Git, so anyone with repo access has every credential.

Prerequisites

  • Ansible with ansible-vault
  • A secure source for the vault password

Steps

1. Encrypt secret variable files and commit only the ciphertext.

Expected output: Secrets are not readable in the repository.

2. Reference the vault password from a secret manager or environment at runtime.

Expected output: The password is not stored beside the ciphertext.

3. Keep secrets in separate files from non-secret variables for reviewability.

Expected output: Plain variables remain diff-friendly.

4. Use vault IDs when multiple passwords are needed.

ansible-vault encrypt group_vars/prod/secrets.yml

Expected output: Different environments use different keys.

Troubleshooting

Problem

Vault password prompted in CI

Solution

Inject the password from CI secrets via --vault-password-file pointing at a decrypted temp file that is removed after use.

Problem

Secret leaks in logs

Solution

Set no_log on tasks handling secrets so values are not echoed.

Limitations

  • Vault encryption protects files at rest but not the decrypted values during a run or in logs.
  • Rotating the vault password requires re-encrypting files, which is a manual, error-prone step.

Context

Manage Ansible secrets with vault-encrypted variable files instead of plaintext. Passwords sit in plaintext group_vars committed to Git, so anyone with repo access has every credential.

Steps

  1. Encrypt secret variable files and commit only the ciphertext. Expected: Secrets are not readable in the repository.
  2. Reference the vault password from a secret manager or environment at runtime. Expected: The password is not stored beside the ciphertext.
  3. Keep secrets in separate files from non-secret variables for reviewability. Expected: Plain variables remain diff-friendly.
  4. Use vault IDs when multiple passwords are needed. Expected: Different environments use different keys.
ansible-vault encrypt group_vars/prod/secrets.yml
ansible-playbook site.yml \
  --vault-password-file <(echo "$VAULT_PASS")

Verify

  • Secrets are not readable in the repository.
  • The password is not stored beside the ciphertext.
  • Plain variables remain diff-friendly.
  • Different environments use different keys.

Limits

  • Vault encryption protects files at rest but not the decrypted values during a run or in logs.
  • Rotating the vault password requires re-encrypting files, which is a manual, error-prone step.