Skip to content

Instantly share code, notes, and snippets.

@pwalkr
Created July 23, 2022 17:33
Show Gist options
  • Save pwalkr/e3c879ca653e0a37770c12350c5e8c5d to your computer and use it in GitHub Desktop.
Save pwalkr/e3c879ca653e0a37770c12350c5e8c5d to your computer and use it in GitHub Desktop.
Ansible shell snippet to have ansible load a vault password from environment
#!/bin/sh
# If not set, tell the user what variable we're looking for.
if [ -z "$SOMETHING" ]; then
echo "Missing vault pass. Set:"
echo " export SOMETHING='SECRET'"
exit
fi
# Ansible checks this variable for executable or password as text.
# Using consistent path helps cleanup, no sensitive data here.
export ANSIBLE_VAULT_PASSWORD_FILE="/tmp/ansible_vault_helper.sh"
# Create password helper script
cat<<'EOF' > "$ANSIBLE_VAULT_PASSWORD_FILE"
#!/bin/sh
echo "$SOMETHING"
EOF
chmod +x "$ANSIBLE_VAULT_PASSWORD_FILE"
# Clean up after ourselves
cleanup() {
rm -f "$ANSIBLE_VAULT_PASSWORD_FILE"
}
trap cleanup 1 2 3 EXIT
@pwalkr
Copy link
Author

pwalkr commented Jul 23, 2022

I use this script as a source include with various ansible wrapper includes in my lab, then I only have to enter my password once per shell (as env). E.g.

# ansible.sh
# Run ansible-playbook with my inventory and given playbook
source ansible_vault_helper.sh
ansible-playbook -i ./inventory "$@"
# vault-encrypt-string.sh
# Encrypt a string for vars file
source ansible_vault_helper.sh
ansible-vault encrypt_string "$2" --name "$1"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment