kubernetes deployment file inject environment variables on a pre script

12/1/2019

I have an elixir app connection to postgres using sql proxy

here is my deployment.yaml I deploy on kubernetes and works well,
the postgres connection password and user name are taken in the image from the environment variables in the yaml

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: my-app
  namespace: production
spec:
  replicas: 1
  revisionHistoryLimit: 1
  strategy:
      type: RollingUpdate
  template:
    metadata:
      labels:
        app: my-app
        tier: backend
    spec:
      securityContext:
        runAsUser: 0
        runAsNonRoot: false
      containers:
      - name: my-app
        image: my-image:1.0.1
        volumeMounts:
        - name: secrets-volume
          mountPath: /secrets
          readOnly: true
        - name: config-volume
          mountPath: /beamconfig
        ports:
        - containerPort: 80
        args:
          - foreground
        env:
        - name: POSTGRES_HOSTNAME
          value: localhost
        - name: POSTGRES_USERNAME
          value: postgres
        - name: POSTGRES_PASSWORD
          value: 123456
        # proxy_container
      - name: cloudsql-proxy
        image: gcr.io/cloudsql-docker/gce-proxy:1.11
        command: ["/cloud_sql_proxy", "--dir=/cloudsql",
            "-instances=my-project:region:my-postgres-instance=tcp:5432",
            "-credential_file=/secrets/cloudsql/credentials.json"]
        volumeMounts:
          - name: cloudsql-instance-credentials
            mountPath: /secrets/cloudsql
            readOnly: true
          - name: cloudsql
            mountPath: /cloudsql
      # volumes
      volumes:
      - name: secrets-volume
        secret:
          secretName: gcloud-json
      - name: cloudsql-instance-credentials
        secret:
          secretName: cloudsql-instance-credentials
      - name: cloudsql
        emptyDir:

now due to security requirements I'd like to put sensitive environments encrypted, and have a script decrypting them
my yaml file would look like this:

env:
- name: POSTGRES_HOSTNAME
  value: localhost
- name: ENCRYPTED_POSTGRES_USERNAME
  value: hgkdhrkhgrk
- name: ENCRYPTED_POSTGRES_PASSWORD
  value: fkjeshfke

then I have script that would run on all environments with prefix ENCRYPTED_ , will decrypt them and insert the dycrpted value under the environment variable without the ENCRYPTED_ prefix

is there a way to do that?
the environments variables should be injected before the image starts running
another requirement is that the pod running the image would decrypt the variables - since its the only one which has permissions to do it (working with work load identity) something like:

- command:
 - sh
 - /decrypt_and_inject_environments.sh
-- dina
kubernetes

0 Answers