0

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!~

4
  • Don't use $(echo $FILE) -- it's an elaborate and error-prone way to do $FILE, because the $( ) and echo mostly cancel each other out. Commented Jan 27, 2022 at 18:38
  • @GordonDavisson, so how would you handle if the filename (that will end up as the var name) has hyphens in it that need to be swapped for underscores? I've presently modified to: declare -xg $(echo $FILE | tr '-' '_')=$(cat $f) -- NOTE: what I've posted is working for the 20(ish) secrets we're loading into our containers... Commented Jan 27, 2022 at 19:30
  • nm... if i need to, i can move it up into the $FILE var creation line. Commented Jan 27, 2022 at 19:47
  • 1
    Using echo this way to feed a pipe is ok, but for a simple substitution like this I'd use ${FILE//-/_}="$(cat $f)" (but note that this type of substitution is a bashism, and won't work in some more basic shells like dash). Commented Jan 27, 2022 at 20:41

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.