0

I am storing passwords (db credentials, aws credentials) and secrets using a third party service (in this case AWS parameter store). I need to build/run a docker image using the parameters stored there, so in my build server I want to run something like:

sed -i 's/AWS_SECRET_KEY/'$aws_secret_key/ Dockerfile

where AWS_SECRET_KEY is a string in a Dockerfile and needs to be replaced by $aws_secret_key, which is a variable containing the real key. Thing is that secret keys, and db passwords are random enough so they contain the '/' symbol. I went through this answer and it looks as the way to go, but I also have a json string that I need to sed, and it contains forward slashes, spaces, double quotes and single quotes. So my question is, is there any method to change a file (doesn't have to be sed) with a string containing random symbols/spaces so it doesn't throw error anytime at replacing time?

1 Answers1

0

(Assuming bash:You'll want to escape the s/// delimiter using Shell Parameter Expansion, regardless of which delimiter you choose.

sed "s,AWS_SECRET_KEY,${aws_secret_key//,/\\,},g" Dockerfile

If you use the default s///, you just need some extra escapes:

sed "s/AWS_SECRET_KEY/${aws_secret_key//\//\\\/}/g" Dockerfile

Demonstrating:

$ cat Dockerfile 
foo AWS_SECRET_KEY bar
$ aws_secret_key="he//o,world"
$ sed "s,AWS_SECRET_KEY,${aws_secret_key//,/\\,},g" Dockerfile
foo he//o,world bar
$ sed "s/AWS_SECRET_KEY/${aws_secret_key//\//\\\/}/g" Dockerfile
foo he//o,world bar

Update:

Based on karakfa's comment, I am missing protecting some characters that are special in the replacement side of the s/// command. For maximum backslash-itis, add a backslash before every non-alphanumeric character:

$ aws_secret_key='he//o,world&\'
$ escaped=$(echo "$aws_secret_key" | sed 's/[^[:alnum:]]/\\&/g')
$ echo "$aws_secret_key"; echo "$escaped"
he//o,world&\
he\/\/o\,world\&\\
$ sed "s/AWS_SECRET_KEY/$escaped/g" Dockerfile
foo he//o,world&\ bar
glenn jackman
  • 238,783
  • 38
  • 220
  • 352