summaryrefslogtreecommitdiff
path: root/ansible-vault-init.sh
blob: 8219ec4c01161ff66d7cccfd5457bda5f91e726a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/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"