ucomesdag

encryptAnsibleVault.sh

Mar 26th, 2022 (edited)
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.36 KB | None | 0 0
  1. #!/usr/bin/env bash
  2.  
  3. function usage(){
  4.   echo "Usage:"
  5.   echo "  $(basename $0) path/to/keyvault.yml 'thepassword'"
  6. }
  7.  
  8. function encrypt(){
  9.   ansible-vault encrypt_string $1 --vault-password-file <(echo $2) | grep -v "Encryption successful"
  10. }
  11.  
  12. [ $# -ne 2 ] && usage && exit;
  13. [ ! -f $1 ] && echo "$file not found!" && exit
  14.  
  15. file=$(realpath $1)
  16. password=$2
  17.  
  18. if [[ $file =~ "[decrypted]" ]]; then
  19.   outfile="${file%%\[decrypted\]*}.${file##*.}"
  20. else
  21.   outfile="$file"
  22. fi
  23.  
  24. yamllint -d "{rules: {line-length: disable}}" "$file"
  25. [ $? -ne 0 ] && echo Failed! && exit
  26.  
  27. tmpfile=$(mktemp)
  28. item=''
  29. s='[[:space:]]*' w='[a-zA-Z0-9_]*' c='^[[:space:]]*#'
  30.  
  31. IFS=''
  32. while read -r line; do
  33.   if [[ ! $line =~ $c ]] && [[ $line =~ $w: ]]; then
  34.     var=$(echo $line | sed "s|^\($s.*\):.*|\1|")
  35.     if [[ ! $var =~ ^$s$w$ ]]; then
  36.       echo "Invalid character(s) used in secret name! (valid: a-zA-Z0-9_.)"
  37.       echo ">> [$item$(echo $var | xargs)]"
  38.       exit 1
  39.     elif [[ $var =~ ^$w$ ]]; then
  40.       item=''
  41.     fi
  42.     val=$(echo $line | sed "s|^$s.*:$s\(.*\)$s\$|\1|")
  43.     if [[ -z $val ]]; then
  44.       echo -e "$line" >> $tmpfile
  45.       item+=$var.
  46.     else
  47.       echo -e "$var: $(encrypt $val $password)" >> $tmpfile
  48.       echo ">> [$item$(echo $var | xargs)]"
  49.     fi
  50.   else
  51.     echo -e "$line" >> $tmpfile
  52.   fi
  53. done <$file
  54.  
  55. mv "$tmpfile" "$outfile"
  56.  
Add Comment
Please, Sign In to add comment