Search code examples
jsonbashamazon-web-servicesjqcredstash

Bash export credstash values from script


So i'm trying to implement a build script that pulls down our credstash keys from DynamoDB and then sets them in the environment running the script, I need to the commands afterward to have access to those environment variables to compile some YML.

Here's what I have(kinda working):

    #!/bin/bash

    creds=$(credstash getall)
    declare -a arrayKeys=($(echo $creds | ./jq '[to_entries[] | .key]' | tr ',' '\n'))

    for ((i=1; i<(${#arrayKeys[*]} -1); i++));
    do
       key=$( printf '%s:' "${arrayKeys[i]}" )
       key=${key%:}

      export key="foo"
    done

This actually seems to run through but when I do printenv after I don't see the keys that I'm after, note I'm setting them to the value foo just to get the iterator stuff working, when this is finished it'll use JQ to pull the value from the JSON I fetched earlier.

Sample JSON:

{
"db.password" : "Some password",
"db.username" : "Some username"
}

Note, as you might be able to tell, I'm no bash scripting expert so this what I've cobbled together after doing a bit of reading.

EDIT

So after the comments below I've now got:

#!/bin/bash

creds=$(credstash getall)
declare -a arrayKeys=($(echo $creds | ./jq --raw-output '[to_entries[] | .key]' | tr ',' '\n'))

for ((i=1; i<(${#arrayKeys[*]} -1); i++));
do
   key=$( printf '%s:' "${arrayKeys[i]}" )
   key=${key%:}
   export eval $key='foo'
done

Which yields:

bash: export: `"db.username"=foo': not a valid identifier

Solution

  • bash + jq solution:

    while read -r key val; do 
        declare -x "$key"="$val"
    done < <(jq -r 'to_entries[] | [(.key | gsub("\\.";"_")), .value] | @tsv' <<<"$creds")
    

    Check declared variable:

    $ echo "$db_username"
    Some username