Skip to content

Instantly share code, notes, and snippets.

@maricn
Last active August 20, 2025 11:56
Show Gist options
  • Select an option

  • Save maricn/ac9724089d30c2f8817b26759b82c9b1 to your computer and use it in GitHub Desktop.

Select an option

Save maricn/ac9724089d30c2f8817b26759b82c9b1 to your computer and use it in GitHub Desktop.
Encrypt values of selected YAML keys with default ansible-vault
#!/bin/bash
# Check if the required command is available
if ! command -v ansible-vault &> /dev/null; then
echo "ansible-vault could not be found. Please install Ansible."
exit 1
fi
# Function to encrypt values in the YAML file
encrypt_values() {
local yaml_file="$1"
local filter_keys="$2"
local reprocess="false"
# Read the YAML file and process it line by line
while [[ $reprocess == true ]] || IFS= read -r line; do
reprocess="false"
# Check if the line contains a key that matches the filter
if [[ $line =~ ^[[:space:]]*([a-zA-Z0-9_]+): ]]; then
key="${BASH_REMATCH[1]}"
# Check if the key matches any of the filter keys
if [[ $key =~ $filter_keys ]]; then
# Handle multiline values
if [[ $line =~ \| ]]; then
# Start collecting multiline value
multiline_value=""
# Determine indentation based on the first next line
IFS= read -r next_line
if [[ "$next_line" =~ ^([[:space:]]*) ]]; then
indentation="${BASH_REMATCH[1]}"
else
indentation=""
fi
multiline_value+="${next_line#"$indentation"}"$'\n'
# Capture the remaining multilines depending on the indentation
while IFS= read -r next_line; do
if [[ "$next_line" == "$indentation"* ]]; then
multiline_value+="${next_line#"$indentation"}"$'\n'
else
reprocess=true
break
fi
done
value=$multiline_value
else
# Extract the value and encrypt it
value=$(echo "$line" | sed 's/^[[:space:]]*[a-zA-Z0-9_]*:[[:space:]]*//')
# Ignore leading and trailing single/double quotation marks
if [[ $value =~ ^[\"\'](.*)[\"\']$ ]]; then
value="${BASH_REMATCH[1]}"
fi
fi
# Replace the line with the encrypted value
encrypted_value=$(ansible-vault encrypt_string "$value")
line="${line%%:*}: $encrypted_value"
fi
fi
echo "$line" >> "$yaml_file.encrypted.yml"
if [[ $reprocess == true ]]; then
line=$next_line
fi
done < "$yaml_file"
}
# Main script execution
if [[ $# -lt 1 ]]; then
echo "Usage: $0 <yaml_file> [--filter <comma_delimited_keys>]"
exit 1
fi
yaml_file="$1"
filter_keys=""
# Parse arguments
while [[ $# -gt 0 ]]; do
case $1 in
--filter)
filter_keys="$2"
shift 2
;;
*)
filter_keys="pass|secret|private|superkey"
shift
;;
esac
done
# Convert filter keys to a regex pattern
if [[ -n $filter_keys ]]; then
filter_keys=$(echo "$filter_keys" | sed 's/,/|/g')
fi
# Encrypt values in the YAML file
echo "########## Encrypted using ./encrypt.sh ##########" > "$yaml_file.encrypted.yml"
encrypt_values "$yaml_file" "$filter_keys"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment