Use Kubernetes secrets as environment variables in Angular 6

2/10/2019

I configured an automatic build of my Angular 6 app and deployment in Kubernetes each time is push to my code repository (Google Cloud Repository).

Dev environment variables are classically store in a environment.ts file like this:

export const environment = {
  production: false,
  api_key: "my_dev_api_key"
};

But I don't want to put my Prod secrets in my repository so I figured I could use Kubernetes secrets.

So, I create a secret in Kubernetes:

kubectl create secret generic literal-token --from-literal api_key=my_prod_api_key

But how to use it in my Angular app?

-- Manuel RODRIGUEZ
angular
kubernetes
kubernetes-secrets

1 Answer

2/10/2019

Nevertheless what you do, your Angular app is a client application i.e. the user's browser downloads the source code of the app (a bunch of CSS/JS/HTML files, images etc.) and it executes it on the user's machine. So you can't hide anything like you do when implementing a client/server app. In client/server applications all the secrets will reside in the server part. If you put the secret in a k8s secret you will not commit it in the repository, but you will expose it to all of your users anyway.

If you still want to populate a configuration based on environment variables (which is a legit use-case), I've seen and used the following approach. The app is Angular 6 and is served to the browser by an nginx server. The startup script in the docker container is a bit odd and looks similar to those lines below:

envsubst < /usr/share/nginx/html/assets/config.json.tpl > /usr/share/nginx/html/assets/config.json
rm /usr/share/nginx/html/assets/config.json.tpl
echo "Configuration:"
cat /usr/share/nginx/html/assets/config.json
nginx -g 'daemon off;'

As you see we've used envsubst to substitute a config template in the assets folder. The config.json.tpl may look like this:

{
  "apiUrl": "${API_URL}"
}

envsubst will substitute the environment variables with their real values and you will have a valid JSON configuration snippet in your assets. Then nginx will then startup.

-- Lachezar Balev
Source: StackOverflow