67 lines
1.6 KiB
Bash
Executable File
67 lines
1.6 KiB
Bash
Executable File
#!/bin/bash
|
|
|
|
# usage: ./ansible-vault-init.sh <? secret-name-to-update>
|
|
|
|
# password input
|
|
while true; do
|
|
read -s -p "Password: " VAULT_PASSWORD
|
|
echo
|
|
read -s -p "Confirm password: " confirmationpwd
|
|
echo
|
|
[ "$VAULT_PASSWORD" = "$confirmationpwd" ] && break
|
|
echo "Please try again"
|
|
done
|
|
|
|
###
|
|
|
|
SECRETS_KEYS_FILE="secrets.txt"
|
|
# temporary secret store
|
|
TEMP_FILE="temp_secrets.yml"
|
|
VAULT_FILE="secrets.enc"
|
|
|
|
if [ "$#" -eq 1 ]; then
|
|
SINGLE_SECRET_MODE=true
|
|
SECRET_TO_UPDATE=$1
|
|
else
|
|
SINGLE_SECRET_MODE=false
|
|
fi
|
|
|
|
|
|
if [ -f "$VAULT_FILE" ]; then
|
|
ansible-vault decrypt "$VAULT_FILE" --output="$TEMP_FILE" --vault-password-file <(echo $VAULT_PASSWORD)
|
|
else
|
|
# create the temporary file
|
|
> "$TEMP_FILE"
|
|
fi
|
|
|
|
IFS=$'\n' read -d '' -r -a secrets < "$SECRETS_KEYS_FILE"
|
|
echo "Gathering secrets..."
|
|
for secret_name in "${secrets[@]}"; do
|
|
if [ "$SINGLE_SECRET_MODE" = true ] && [ "$secret_name" != "$SECRET_TO_UPDATE" ]; then
|
|
continue
|
|
fi
|
|
|
|
if grep -q "^$secret_name:" "$TEMP_FILE"; then
|
|
if [ "$SINGLE_SECRET_MODE" = true ]; then
|
|
# Remove the old value of the secret
|
|
sed -i "/^$secret_name:/d" "$TEMP_FILE"
|
|
else
|
|
echo "Secret $secret_name already exists, skipping."
|
|
continue
|
|
fi
|
|
fi
|
|
|
|
echo -n "Enter value for $secret_name: "
|
|
read secret_value
|
|
echo "$secret_name: $secret_value" >> "$TEMP_FILE"
|
|
done
|
|
|
|
echo "Re-encrypting secrets..."
|
|
|
|
ansible-vault encrypt "$TEMP_FILE" --output="$VAULT_FILE" --vault-password-file <(echo $VAULT_PASSWORD)
|
|
|
|
# remove the temp secrets file securely
|
|
shred -u "$TEMP_FILE"
|
|
|
|
echo "Secrets have been encrypted into secrets.enc"
|