Back to the main page

Ansible vault


Ansible vault is used to encrypt variables and files. The use case is that you want to have code in source code remote repo (ex. git), so secret/password are encrypted there.
In this demo, we'll use vault to encrypt user's password.

Role code

There is the role "user", which creates local user.
The vars/main.yml contains user's password, example:
mypassword: "$6$MShlKf---TGBeyVcMg.jEw4w7/"

The tasks/main.yml reads role's tasks. The 2nd task uses variable 'mypassword'.
- name: Add vault-group group
    name: vault-group
    state: present
    gid: 60000
- name: Add user vault-user
    name: vault-user
    uid: 600000
    group: vault-group
    comment: User to test ansible-vault
    shell: /bin/bash
    home: /tmp/vault-user
    password: "{{ mypassword }}"


Creating hashed password

This is one of ways to create hashed password (ex. my-passwd).
$ ansible all -i localhost, -m debug -a "msg={{ 'my-passwd' | password_hash('sha512') }}"

localhost | SUCCESS => {
    "msg": "$6$F/h8ASFD5........oAGhASt/"

Encrypt a file

Example, encrypt variable main file, provide *vault* password.
$ ansible-vault encrypt user/vars/main.yml

New Vault password:  < my-vault-passwd >
Confirm New Vault password: < my-vault-passwd >
Encryption successful

Decrypt a file

Example, decrypt variable main file, provide *vault* password.
$ ansible-vault decrypt user/vars/main.yml

Vault password: < my-vault-passwd >
Decryption successful

View encrypted file

$ ansible-vault view user/vars/main.yml
Vault password:

Rekey (change encryption key)

$ ansible-vault rekey user/vars/main.yml
Vault password:
New Vault password:
Confirm New Vault password:
Rekey successful

Edit encrypted file

$ ansible-vault edit user/vars/main.yml
Vault password:

Run playbook after files is encrypted

$ ansible-playbook -i inventory  user.yml --ask-vault-pass
Vault password:

Run playbook with vault passwd in file

$ ansible-playbook -i inventory  user.yml --vault-password-file=.vault-secret

Back to the main page