Ansible encrypt and decrypt the secure fields

Wrap the ansible vault scripts

 1#!/usr/bin/env bash
 2
 3[ "$#" -gt 2 ] || {
 4  echo "Usage $0 encrypt|decrypt option..."
 5  echo "Must be least three argumeents required"
 6  exit 1
 7}
 8
 9#the decrypt key file path, also can put the aws ssm
10vault_id='/opt/ansible_pass'
11
12
13function encrypt() {
14  ansible-vault encrypt_string --vault-password-file $1 $2 --name $3
15}
16
17function decrypt() {
18  ansible -i $1 $2 -m ansible.builtin.debug -a var="${3}" -e $4 --vault-id $5
19}
20
21case "$1" in 
22  encrypt)
23    shift 1
24    [ "$#" -eq 2  ] || {
25      echo "Usage $0 encrypt 'plain string' 'field name'"
26      exit 1
27    }
28    encrypt $vault_id  $1  $2
29	;;
30  decrypt)
31    shift 1
32    [ "$#" -eq 4 ] || {
33      echo "Usage $0 decrypt 'inventory' 'host' 'field name' 'var file name' to decrypt content"
34      exit 1
35    }
36    inventory_path=$1
37    host=$2
38    field_name=$3
39    var_file=$4
40    decrypt $inventory_path  $host $field_name var_file  $vault_id
41	;;
42  *)
43    echo "Arguments is error..."
44    exit 1
45	;;
46esac
  • Usage steps and instructions
 1# put the encrypt keys to secure path in current machine, don't commit to git or remote repos
 2echo "xxxxx" > /opt/ansible_pass
 3
 4# encrypt the field password
 5# usage ./exec.sh encrypt plain_pass field_name
 6./exec.sh encrypt xxxx ansible_ssh_password
 7
 8# view the plain value for encrypt items
 9#./exec.sh decrypt inventories/path host_var encrypt_field the_file_name_host_vars_file
10./exec.sh decrypt inventories/newyork nexus ansible_ssh_password nexus 
11
12# play arguments for vault-id to AES key path
13 ansible-playbook -i inventories/pairs site.yml --extra-vars "target_server=bastion" --vault-id /opt/ansible_pass