#TIL - envsubst command

I was doing some bashscript work to generate yaml files from simple templates to be able to use in GitLab CI jobs. First thing that I did was using sed command and replaced variables in yml like this:

sed "s/\${SERVICE_DOMAIN}/$SERVICE_DOMAIN/g; s/\${SERVICE_NAME}/$SERVICE_NAME/g" template.yml

Replacing some variables inside a file with sed command

This works but when you add more variables and especially if values includes some chars that breaks regex rule, then it's not helpful anymore.

Then I found awesome envsubst command in a stackoverflow thread.

$ cat template.yml
services:
  ${SERVICE_NAME}:
    environment:
      url: ${MAIN_URL}
    ...

$ MAIN_URL=https://muratcorlu.com

$ SERVICE_NAME=muratcorlu

$ export MAIN_URL SERVICE_NAME

$ cat template.yml | envsubst
services:
  muratcorlu:
    environment:
      url: https://muratcorlu.com
    ...

Using envsubst command to replace env variables inside a file

This is so much cleaner! I loved it!

Me on Mastodon: https://synaps.space/@murat