Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create environment variables for Kubernetes main container in Kubernetes Init container

I use an Kubernetes Init container to provision the application's database. After this is done I want to provide the DB's credentials to the main container via environment variables.

How can this be achieved?

I don't want to create a Kubernetes Secret inside the Init container, since I don't want to save the credentials there!

like image 789
vuza Avatar asked Mar 30 '18 09:03

vuza


People also ask

Do containers in pod share environment variables?

Short answer is No, they can't.


1 Answers

I see several ways to achieve what you want:

  1. From my perspective, the best way is to use Kubernetes Secret. @Nebril has already provided that idea in the comments. You can generate it by Init Container and remove it by PreStop hook, for example. But, you don't want to go that way.

  2. You can use a shared volume which will be used by InitConatainer and your main pod. InitContainer will generate the environment variables file db_cred.env in the volume which you can mount, for example, to /env path. After that, you can load it by modifying a command of your container in the Pod spec and add the command source /env/db_cred.env before the main script which will start your application. @user2612030 already gave you that idea.

  3. Another alternative way can be Vault by Hashicorp, you can use it as storage of all your credentials.

  4. You can use some custom solution to write and read directly to Etcd from Kubernetes apps. Here is a library example - k8s-kv.

But anyway, the best and the most proper way to store credentials in Kubernetes is Secrets. It is more secure and easier than almost any other way.

like image 84
Anton Kostenko Avatar answered Oct 08 '22 04:10

Anton Kostenko