Created
December 15, 2022 09:47
-
-
Save kchenery/60a5c41fb7e10e5690e1209e074656ad to your computer and use it in GitHub Desktop.
Initialise Hashicorp Vault and capture keys
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/bash | |
if [[ -z "${VAULT_ADDR}" ]]; then | |
echo "VAULT_ADDR is not defined" | |
fi | |
if [[ -z "${VAULT_KEY_COUNT}" ]]; then | |
VAULT_KEY_COUNT=5 | |
fi | |
if [[ -z "${VAULT_KEY_REQUIRED}" ]]; then | |
VAULT_KEY_REQUIRED=3 | |
fi | |
# Wait for Vault | |
echo "Testing if Vault is available..." | |
MAX_CURL_ATTEMPTS=2 | |
until curl --silent --fail --output /dev/null $VAULT_ADDR/v1/sys/init | |
do | |
sleep 5 | |
((MAX_CURL_ATTEMPTS=MAX_CURL_ATTEMPTS - 1)) | |
if [ $MAX_CURL_ATTEMPTS = 0 ]; then | |
echo "Cannot connect to Vault. I am giving up" | |
exit 1 | |
fi | |
echo "Attempting to contact Vault again. Attempts remaining: ${MAX_CURL_ATTEMPTS}" | |
done | |
# Check if Vault is already initialised and exit if it is | |
VAULT_INITIALISED=$( curl --silent $VAULT_ADDR/v1/sys/init | jq --raw-output '.initialized' ) | |
if [[ ${VAULT_INITIALISED} = "true" ]]; then | |
echo "Vault has already been initialised" | |
exit 0 | |
fi | |
# Initialise Vault and capture keys and root token | |
echo "Initialising Vault" | |
INIT_RESULT=$( curl --silent --request POST --data "{\"secret_shares\": ${VAULT_KEY_COUNT}, \"secret_threshold\": ${VAULT_KEY_REQUIRED} }" $VAULT_ADDR/v1/sys/init ) | |
KEYS=$( echo $INIT_RESULT | jq --raw-output '.keys_base64[]' ) | |
ROOT_TOKEN=$( echo $INIT_RESULT | jq --raw-output '.root_token' ) | |
# Build JSON for AWS Secret | |
JSON_SECRET="{\"root_token\": \"${ROOT_TOKEN}\"" | |
for ((id=0; id<VAULT_KEY_COUNT; id++)) { | |
KEY=$( echo $KEYS | awk -v id=$((id+1)) '{ print $id }' ) | |
JSON_SECRET=$( echo "${JSON_SECRET}, \"init-key-${id}\":\"${KEY}\"" ) | |
} | |
JSON_SECRET="${JSON_SECRET}}" | |
# Put AWS Secret | |
echo $JSON_SECRET | jq |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment