Skip to content

Instantly share code, notes, and snippets.

@zoredache
Created March 13, 2018 18:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zoredache/6f8edc9f4de239e4d18508ff8164d271 to your computer and use it in GitHub Desktop.
Save zoredache/6f8edc9f4de239e4d18508ff8164d271 to your computer and use it in GitHub Desktop.
ansible gpg vault script
#!/bin/bash
# adapted from https://github.com/yaegashi/ansible-snippets/blob/master/gnupg/ansible-gpg-file.sh
# ansible.cfg
# [defaults]
# # decryption passphrase and key in lastpass
# vault_password_file = ./gpg-vault-file.sh
if [ -z "$GPG_TTY" ]; then
echo "The GPG_TTY variable must be set!"
cat << EOF
# /etc/profile.d/gpg_tty.sh
# https://www.gnupg.org/documentation/manuals/gnupg/Invoking-GPG_002dAGENT.html
# You should always add the following lines to your .bashrc or whatever
# initialization file is used for all shell invocation
GPG_TTY=\$(tty)
export GPG_TTY
EOF
exit 1
fi
if [ ! -f ~/.gnupg/gpg.conf ]; then
echo "missing gpg.conf"
cat << EOF
# ~/.gnupg/gpg.conf
use-agent
cipher-algo aes256
EOF
exit 1
fi
set -eu
gpg_bin=$(which gpg)
gpg_connect_agent=$(which gpg-connect-agent)
# start the agent, or fail if unable to start since `set -e`
$gpg_connect_agent /bye
usage() {
cat <<EOF
Usage:
$program [options]
Options:
-h Show this help
-d Decrypt embedded content in this script and print it (default)
-p Print embedded content in this script
-r FILE Print updated script with embedded content replaced with FILE
-i Used with -r, in-place replace $0
Notes:
You need to feed embedded content in ASCII-armored format for -r.
You should specify -a to gpg for encryption as the following example.
Example:
\$ echo secret-content | gpg -ac | $0 -ir -
\$ $0
secret-content
EOF
exit $1
}
program=${0##*/}
args=$(getopt -o dpr:ih -n $program -- "$@")
test $? -eq 0 || usage 1
eval set -- "$args"
MODE=DECRYPT
FILE=-
INPLACE=false
while test $# -gt 0; do
case "$1" in
-d)
MODE=DECRYPT
shift
;;
-p)
MODE=PRINT
shift
;;
-r)
MODE=REPLACE
FILE=$2
shift 2
;;
-i)
INPLACE=true
shift
;;
-h)
usage
;;
--)
shift
break
;;
*)
usage 1
;;
esac
done
case "$MODE" in
DECRYPT)
$gpg_bin -q -d $0
;;
PRINT)
sed -e '1,/^# EMBED /d' $0
;;
REPLACE)
TEMPFILE=$(tempfile)
trap "rm -f $TEMPFILE" EXIT
sed -ne '1,/^# EMBED /p' $0 >$TEMPFILE
cat "$FILE" >>$TEMPFILE
if $INPLACE; then
chmod +x $TEMPFILE
mv $TEMPFILE $0
else
cat $TEMPFILE
fi
;;
esac
exit $?
# EMBED SECURE CONTENT IN ASCII-ARMORED FORMAT BELOW
-----BEGIN PGP MESSAGE-----
...
-----END PGP MESSAGE-----
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment