Environment Variables

How to add and use a new environment variable

There are times when we need to add a new environment variable to be used later in the running pods of a website. Either to adjust some functionality based on its value or to pass a secret.

Code changes

This involves a series of small changes across 3 of our code repositories.

Helm Chart

First we need to add the new variable in the repository that builds the WordPress helm chart, making the necessary changes to two specific files.

templates/deployment-php.yaml: inside the env block:

- name: MY_API_KEY
  valueFrom:
    secretKeyRef:
      name: "{{ .Release.Name }}-keysalt"
      key: myApiKey

templates/secrets-wp-keysalt.yaml: inside the data block:

myApiKey: {{ .Values.myApiKey | quote }}

💻 commit example

Docker

Next we need to add it in our docker repository.

src/planet-4-151612/wordpress/templates/Dockerfile.in; inside the ENV block:

MY_API_KEY=""

src/planet-4-151612/wordpress/wp-config.php.tmpl:

{{ if .Env.MY_API_KEY }}
define( 'MY_API_KEY', '{{ .Env.MY_API_KEY }}' ); 
{{ end }}

💻 commit example

Builder

When both of the above changes are merged, we need to make a change on our builder repository.

We need to use the new Helm chart version, so it's important to wait for the change we did above to that repository to complete its CI pipeline that creates a new tag and then use that tag as the Chart version.

src/var/secrets.yaml.in:

myApiKey: '${MY_API_KEY}'

src/Makefile: adding the new helm chart version:

CHART_VERSION ?= 0.8.34

💻 commit example

CircleCI

To start using that variable we need to add it in CircleCI as an environment variable with the value we want. Either in the global context, if it's meant to be used globally, or to a specific project environment variables screen.

The variables are base64 hashed, so before adding its value you need to create it and use that one instead:

echo "my_secret_variable_value" | base64

Even if the output is split into lines, make sure to delete the new line characters and enter it in one line in CircleCI.

Theme

Finally you can read the value of that variable in the theme, either in the main one or in a child theme.

Last updated