kubetpl icon indicating copy to clipboard operation
kubetpl copied to clipboard

Add support for environment variables

Open chroche opened this issue 5 years ago • 2 comments

kubetpl should be able to interpolate environment variables that appear in the source template, similarly to what envsubst does, possibly with an option like --with-env.

My use case is that I'm collecting secrets from AWS SecretsManager and storing them in environment variables in a Makefile. I would like to be able to write something like this:

fetch_secret = $(shell aws secretsmanager get-secret-value --secret-id '$(1)' --output text --query SecretString)

my_file_1.yaml: export SECRET1 = $(call fetch_secret, this_secret)
my_file_2.yaml: export SECRET2 = $(call fetch_secret, that_secret)

%.yaml: %.tpl
	kubetpl render $< -c . -i $(VALUES_FILE) --with-env -o $@

Values obtained this way would probably have the lowest priority, after -s and -i values.

chroche avatar Apr 04 '19 17:04 chroche

+1

I'm also finding this could be beneficial in CI pipelines where information is provided as environment variables.

Say for example there is a variable $BRANCH that is set within your pipeline. Sure there are workarounds like:

a) Redeclare and pass in using -s BRANCH=$BRANCH. Not bad but gets messy as you add more vars. b) Add a step in the pipeline to first render a file (perhaps using envsubst) and pass this to kubetpl using -i.

Neither is really ideal. It would be great to have an option to interpolate environment vars within the template file itself, and possibly for any -i files as well.

cotej avatar Jul 12 '19 01:07 cotej

This is my solution:

templates_dir = ./templates
spec_dir = ./spec
spec = out.yml
flags = --freeze

templates = $(wildcard $(templates_dir)/*.template.yml)

.PHONY: all
all: compile
		
.PHONY: compile
compile: $(spec_dir) $(spec_dir)/.env $(spec_dir)/$(spec)

.PHONY: clean
clean:
	rm -f $(spec_dir)/.env $(spec_dir)/$(spec)	
	rmdir $(spec_dir)

.PHONY: install
install:
	kubectl apply -f $(spec_dir)/$(spec)

$(spec_dir): $(shell mkdir -p $(spec_dir))

$(spec_dir)/.env: $(shell env > $(spec_dir)/.env)

$(spec_dir)/$(spec): $(templates)
	kubetpl render $^ -o $@ -i $(spec_dir)/.env $(flags)

conradoqg avatar May 23 '20 13:05 conradoqg