PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 21, 2022

[FIXED] How to render variables into a target file from differnet dotenv environment files like envsubst

 August 21, 2022     environment-variables, kubernetes, shell     No comments   

Issue

I have all my env vars in .env files. They get automatically loaded when I open my shell-terminal.

I normally render shell environment variables into my target files with envsubst. similar to the example below.

What I search is a solution where I can pass a dotenv-file as well my template-file to a script which outputs the rendered result.

Something like this:

aScript --input .env.production --template template-file.yml --output result.yml

I want to be able to parse different environment variables into my yaml. The output should be sealed via "Sealed secrets" and finally saved in the regarding kustomize folder

envsub.sh .env.staging templates/secrets/backend-secrets.yml | kubeseal -o yaml > kustomize/overlays/staging

I hope you get the idea.


example

.env.production-file:

FOO=bar PASSWROD=abc

content of template-file.yml

stringData:
  foo: $FOO
  password: $PASSWORD

Then running this:

envsubst < template-file.yml > file-with-vars.yml

the result is:

stringData:
  foo: bar
  password: abc

My approach so far does not work because Dotenv also supports different environments like .env, .env.production, .env.staging asf..


Solution

What about:

#!/bin/sh

# envsub - subsitute environment variables

env=$1
template=$2

sh -c "
. \"$env\"

cat <<EOF
$(cat "$template")
EOF"

Usage:

./envsub .env.production template-file.yaml > result.yaml
  • A here-doc with an unquoted delimiter (EOF) expands variables, whilst preserving quotes, backslashes, and other shell sequences.
  • sh -c is used like eval, to expand the command substitution, then run that output through a here-doc.
  • Be aware that this extra level of indirection creates potential for code injection, if someone can modify the yaml file.

For example, adding this:

EOF
echo malicous commands

But it does get the result you want.



Answered By - dan
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing