thepip3r
thepip3r

Reputation: 2935

Bash: Dynamically create environment variables

We're delivering secrets into our containers via a path, e.g.: /mnt/secrets

...and each subsequent file in that directory is the 'secret' with the contents being the value: e.g. /mnt/secrets/somepassword contains 'superdooperpassword123'

This is happening because we're managing our secrets from a secret-store provider (encrypted, etc.). However, I need to convert those files+filecontents to environment variables to be used in other scripts.

Here is the script I attempted to use to accomplish that, secrets.sh:

FILES="/mnt/secrets/*"
for f in $FILES
do
  FILE=$(basename $f)
  echo "Creating environment variable for the following secret:  $FILE"
  declare -xg $(echo $FILE)=$(cat $f)
done

And while this runs without error, I don't see (via 'set' or get nothing with 'echo $var') when I try to ensure they're available. I've tried multiple arguments for 'declare' but I can't seem to expose the declared variables running in secrets.sh (from the files and their contents) back to bash.

I know I'm probably missing something simple. Any assistance would be appreciate to direct me how to use a shell script that reads files and their contents from the filesystem into dynamically created environment variables. TIA!~

Upvotes: 0

Views: 120

Answers (1)

Diego Torres Milano
Diego Torres Milano

Reputation: 69218

You have to source the file

source secrets.sh

or

. secrets.sh

otherwise you are setting the variables of the child process which are not the same as the parent's

Upvotes: 1

Related Questions