Kubernetes - Passing in environment variable and service name (from DNS)

5/21/2018

I can't seem to find an example of the correct syntax for inserting a environment variable along with the service name:

So I have a service defined as:

apiVersion: v1
kind: Service
metadata:
  name: test
spec:
  type: NodePort
  ports:
  - name: http
    port: 3000
    targetPort: 3000
  selector:
    app: test

I then use a secrets file with the following:

apiVersion: v1
kind: Secret
metadata:
  name: test
  labels:
    app: test
data:
  password: fxxxxxxxxxxxxxxx787xx==

And just to confirm I'm using envFrom to set that password as an env variable:

apiVersion: v1
kind: Deployment
metadata:
  name: test
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: test
    spec:
      containers:
        - name: test
          image: xxxxxxxxxxx
          imagePullPolicy: Always
          envFrom:
          - configMapRef:
              name: test
          - secretRef:
              name: test
          ports:
            - containerPort: 3000

Now in my config file I want to refer to that password as well as the service name itself - is this the correct way to do so:

apiVersion: v1
kind: ConfigMap
metadata:
  name: test
  labels:
    app: test
data:
  WORKING_URI: "http://somedomain:${password}@test" 
-- userMod2
kubernetes

1 Answer

5/21/2018

The yaml configuration does not work the way you provided as an example.

If you want to setup Kubernetes with a complex configuration and use variables or dynamic assignment to some of them, you have to use an external parser to replace variable place holders. I use bash and sed to accomplish it. I changed your config a bit:

apiVersion: v1
kind: ConfigMap
metadata:
  name: test
  labels:
    app: test
data:
  WORKING_URI: "http://somedomain:VAR_PASSWORD@test"

After saving, I created a simple shell script containing desired values.

#!/bin/sh

export PASSWORD="verysecretpwd"
cat deploy.yaml | sed "s/VAR_PASSWORD/$PASSWORD/g" | kubectl -f -
-- d0bry
Source: StackOverflow