Skip to content

Instantly share code, notes, and snippets.

@jerm
Created November 16, 2017 21:57
Show Gist options
  • Save jerm/afe11cdafeb2e2f21708ded8c0ba64df to your computer and use it in GitHub Desktop.
Save jerm/afe11cdafeb2e2f21708ded8c0ba64df to your computer and use it in GitHub Desktop.
Make ansible vault files greppable
### Ansible vault grepping
export VAULTS_LIST_FILE='.vaults.txt'
vaultscan()
{
echo "Scanning `pwd` for ansible-vault files"
[ -n "$VAULTSCANBASE" ] && pushd "$VAULSCANBASE"
true > $VAULTS_LIST_FILE
IFS=$'\n'
set -f
for i in `find . -type f`
do
if head -1 "$i" | grep -q '$ANSIBLE_VAULT'; then
echo "Found vault $i"
echo "$i" >> $VAULTS_LIST_FILE
fi
done
set +f
[ -n "$VAULTSCANBASE" ] && popd
}
_vaultgrep(){
_searchfor="$1"
_vaultfile="$2"
OUTPUT=$(ansible-vault view "$_vaultfile" | grep "$_searchfor")
if [ -n "$OUTPUT" ]; then
echo
echo "$_vaultfile:$OUTPUT"
else
echo -n '.'
fi
}
vaultgrep()
{
[ -z "$1" ] && echo "# ERROR: Need a search string!" && return 1
searchfor="$1"
if [ -z "$2" ]; then
[ -n "$VAULTSCANBASE" ] && pushd "$VAULSCANBASE"
[ -f "$VAULTS_LIST_FILE" ] || vaultscan
while read -r vaultfile
do
_vaultgrep "$searchfor" "$vaultfile"
done < $VAULTS_LIST_FILE
[ -n "$VAULTSCANBASE" ] && popd
else
vaultfile="$2"
_vaultgrep "$searchfor" "$vaultfile"
fi
}
@jerm
Copy link
Author

jerm commented Apr 10, 2025

that's super-cool! definitely more streamlined if you have a vault naming convention, AND it's in git

somehow i just now saw this... 5+ years later ๐Ÿ˜‚

thanks @packetfairy ! ๐Ÿ™‚

@jerm
Copy link
Author

jerm commented Apr 10, 2025

If you don't have a naming convention, but all your vaults are in git, this is a streamlined version that doesn't need the vaultscan() anymore

_vaultgrep(){

    _searchfor="$1"
    _vaultfile="$2"

    OUTPUT=$(ansible-vault view "$_vaultfile" 2>&1 | grep -v CryptographyDeprecationWarning | grep "$_searchfor")

    if [ -n "$OUTPUT" ]; then
        echo
        echo "$_vaultfile:$OUTPUT"
    else
        echo -n '.'
    fi
}
vaultgrep()
{
    [ -z "$1" ] && echo "# ERROR: Need a search string!" && return 1
    searchfor="$1"
    if [ -z "$2" ]; then
        #while read -r vaultfile
        for vaultfile in $(git grep -H '$ANSIBLE_VAULT' * | cut -f1 -d ':')
        do
            _vaultgrep "$searchfor" "$vaultfile"
        done
    else
        vaultfile="$2"
        _vaultgrep "$searchfor" "$vaultfile"
    fi
}

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