1

I'm trying to come up with a way of parameterizing some config files for a docker image using env vars. A sample input file could look something like:

<database>
  <host>${DB_HOST}</host>
  <name>${DB_NAME}</name>
  <user>${DB_USER}</user>
  <pass>${DB_PASSWORD}</pass>
</database>

and I'd want the output to basically be exactly the same, but with the fields filled in with the corresponding environment variable value.

Is there a simple way to do this directly in bash? The system I'm using doesn't natively support env vars, so I need to write these config files by hand, but I need to inject different vars for each environment I'm in so I don't particularly want to actually maintain real files for each env.

3 Answers 3

2

This is that simple as :

cat<<EOF > new_config_file
<database>
  <host>${DB_HOST}</host>
  <name>${DB_NAME}</name>
  <user>${DB_USER}</user>
  <pass>${DB_PASSWORD}</pass>
</database>
EOF

ls -l new_config_file
Sign up to request clarification or add additional context in comments.

1 Comment

while I prefer that your solution doesn't have any package dependencies, technically I was asking about an existing file, not a heredoc, but this is also a great answer, thanks so much!
1

you're looking for envsubst

$ envsubst < config_template > config_instance

Comments

0

Just another option.

My generated config files often require just a bit of logic + embedding environment variable contents. At some point I got tired of reinventing the wheel every time and stitched together a simple tool in Go called Templater (https://github.com/reertech/templater).

It's just a standalone zero dependency binary for most of the systems, so you can just download it and use Go templating language (https://golang.org/pkg/text/template/) like that:

#!/bin/bash

YEAR=1997 \
NAME=John \
SURNAME=Connor \
./templater -t - -o /tmp/hello.txt <<EOF
Hello, {{env "NAME"}} {{env "SURNAME"}}!
{{ if env "YEAR" | parseInt | eq 1997 }}
Have a nice Judgement Day!
{{ end }}
EOF

In case you're not comfortable with prebuilt binaries you can use Go and build one yourself.

Hope this helps you or someone else who cannot cut it with just environment substitution and doesn't feel like Bashing.

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.