jolbax
3/17/2017 - 6:09 AM

Encrypt SaltStack Pillars #saltstack #encryption #pillar

Encrypt SaltStack Pillars #saltstack #encryption #pillar

#!/usr/bin/env bash
# Usage: salt-encrypt {optional -f} <input> <keyid>, or just `salt-encrypt` for interactive mode
# Summary: Encrypt some string / file for Salt
# Help: This command can be used to gpg encrypt some content for use in salt pillars or really anything you want to encrypt with GPG

set -e

#Replace below with the default key you encrypt with
DEFAULT_RECIPIENT="XXXXXX" 
multi=0

if [[ -z "$1" ]]; then
    echo Enter the text you want to encrypt and end with a line with a single dot on it

    while read -r line
    do
      if [ "$line" == "." ]; then
        break
      else
        plaintext+=$line
        plaintext+=$'\n'
        ((multi++ ))
      fi
    done

    # This will strip the last newline
    plaintext=$(echo "$plaintext" | sed -e 's/[[:space:]]*$//')

    if [[ -z "$plaintext" ]]; then
        echo You must specify something to encrypt
        exit
    fi

    echo Now enter the recipient KeyID you\'d like to use - leave blank to use default
    read recipient_keyid

    echo Encrypting your data now
    echo ........................
    echo ........................

    echo $multi
    if [[ -z "$recipient_keyid" ]]; then
      if [ "$multi" -gt "1" ]; then
        echo "$plaintext" | gpg --trust-model always --armor --encrypt -r $DEFAULT_RECIPIENT
        echo "multi"
      else
        echo -n "$plaintext" | gpg --trust-model always --armor --encrypt -r $DEFAULT_RECIPIENT
      fi
      exit
    else
        if [ "$multi" -gt 1 ]; then
          echo "$plaintext" | gpg --trust-model always --armor --encrypt -r $recipient_keyid
        else
          echo -n "$plaintext" | gpg --trust-model always --armor --encrypt -r $recipient_keyid
        fi
        exit
    fi
fi

case "$1" in
'-f')
if [[ -z "$3" ]]; then
    cat $2 | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' | gpg --trust-model always --armor --encrypt -r $DEFAULT_RECIPIENT
    exit
else
    cat $2 | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' | gpg --trust-model always --armor --encrypt -r $3
    exit
fi
;;
*)
if [[ -z "$3" ]]; then
    echo -n $2 | gpg --trust-model always --armor --encrypt -r $DEFAULT_RECIPIENT
    exit
else
    echo -n $2 | gpg --trust-model always --armor --encrypt -r $3
    exit
fi
;;
esac