Working with secrets using Ansible

Published:
Translations:no translations yet

Secrets in your yaml-files should be encrypted. The default Ansible method encrypts an entire file, but it’s inconvenient in practice. It’s much better to encrypt specific variables. It makes Ansible code easier to analyze as you can see encrypted variable name. And it’s nice to run your playbook without vault key if the secret variable is unused during play.

Ansible documentation mentions variable-level encryption but offers no oneliner solution.

Visual Studio Code has a nice plugin, ansible-vault-inline. It allows you to edit encrypted values in yaml files.

If you want to use it in your shell:

decrypt_secret () {
    if [[ -z "$3" ]]; then
        VAULT_PASS_FILE="~/.vault_pass"
    else
        VAULT_PASS_FILE="$3"
    fi
    yq read $1 $2 | ansible-vault decrypt --vault-password-file "$VAULT_PASS_FILE" ;}

encrypt_secret () {
    if [[ -z $2 ]]; then
        VAULT_PASS_FILE="~/.vault_pass"
    else
        VAULT_PASS_FILE="$2"
    fi
    echo -n "$1" | ansible-vault encrypt_string --vault-password-file "$VAULT_PASS_FILE" ;}

Usage:

decrypt_secret <var_file_name> <var_name> <vault_key_file_name>
encrypt_secret <secret_string> <vault_key_file_name>