Ansible: How to encrypt some variables in an inventory file in a separate vault file

ansibleansible-playbookansible-vaultencryption

The settings

Consider an Ansible inventory file similar to the following example:

[san_diego]
host1
host2

[san_francisco]
host3
host4

[west_coast]
san_diego
san_francisco

[west_coast:vars]
db_server=foo.example.com
db_host=5432
db_password=top secret password

The problem

I would like to store some of the vars (like db_password) in an Ansible vault, but not the entire file.

How can a vault-encrypted ansible file be imported into an unencrypted inventory file?

What I've tried

I have created an encrypted vars file and tried importing it with:

include: secrets

To which ansible-playbook responded with:

ERROR: variables assigned to group must be in key=value form

Probably because it tried to parse the include statement as a variable.

Best Solution

Since Ansible 2.3 you can encrypt a Single Encrypted Variable. IMO, a walkthrough is needed as the doco's seem pretty terse.

Given an example of: mysql_password: password123 (within main.yml)

Run a command such as:

ansible-vault encrypt_string password123 --ask-vault-pass

This will produce:

    !vault |
$ANSIBLE_VAULT;1.1;AES256
66386439653236336462626566653063336164663966303231363934653561363964363833
3136626431626536303530376336343832656537303632313433360a626438346336353331
Encryption successful

paste this into your main.yml:

mysql_password: !vault |
    $ANSIBLE_VAULT;1.1;AES256
    66386439653236336462626566653063336164663966303231363934653561363964363833
    3136626431626536303530376336343832656537303632313433360a626438346336353331

run playbook:

Ie, ansible-playbook -i hosts main.yml --ask-vault-pass

Verify via debug:

- debug:
    msg: "mysql Pwd: {{ mysql_password }}"