Last active
November 24, 2023 11:25
-
-
Save toms-place/6f0e2f3f2c50c501357780af2a46ad96 to your computer and use it in GitHub Desktop.
Sourcing Environment Variables from Hashicorp Vault with bash
This file contains hidden or 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
#!/bin/bash | |
#TODO: add support for multiple environments | |
#TODO: add support for multiple vaults | |
#TODO: add support for multiple paths in vault | |
ENVIRONMENT=prod | |
appendSecretsFromBucketToEnvFile(){ | |
bucket=$1 | |
envFile=$2 | |
# convert bucket name to uppercase and replace . with _ and - with _ | |
bucket_upper=$(echo $bucket | tr [:lower:] [:upper:] | tr . _ | tr - _) | |
# store secrets as json | |
bucket_json=$(vault kv get -format=json -field data -mount=$ENVIRONMENT $bucket | jq -cr) | |
# loop over secrets and append them to the env file | |
for secret in $(echo ${bucket_json} | jq -cr 'to_entries | .[].key'); do | |
printf "export %s=%s" \ | |
${bucket_upper}_${secret} \ | |
"$(echo ${bucket_json} | jq -c --arg s ${secret} '.[$s]')" \ | |
>> $envFile | |
done | |
} | |
sourceEnvFromVault(){ | |
envFile=$(mktemp) | |
# do this in paralell to speed up the second call to vault | |
for bucket in $(vault kv list -format=json $1 | jq -cr '.[]'); do | |
appendSecretsFromBucketToEnvFile $bucket $envFile & | |
done | |
wait | |
source $envFile | |
rm $envFile | |
} | |
start=$(date +%s) | |
sourceEnvFromVault $ENVIRONMENT | |
end=$(date +%s) | |
echo | |
printenv | |
echo | |
echo Sourcing took $(expr $end - $start) seconds | |
echo ENV: $ENVIRONMENT |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment