How to use environment variables in init container args in kubernetes/openshift?

11/13/2018

This is an excerpt of my deployment config:

...
spec:
  containers:
    - env:
        - name: GIT_USERNAME
          valueFrom:
            secretKeyRef:
              key: username
              name: git
        - name: GIT_PASSWORD
          valueFrom:
            secretKeyRef:
              key: password
              name: git
  initContainers:
    - args:
        - clone
        - '--single-branch'
        - '--'
        - 'https://$(GIT_USERNAME):$(GIT_PASSWORD)@someurl.com/something.git'
        - '/testing/'
      image: alpine/git
      imagePullPolicy: Always
      name: init-clone-repo
      resources: {}
      terminationMessagePath: /dev/termination-log
      terminationMessagePolicy: File
      volumeMounts:
        - mountPath: /testing
          name: test-volume
  volumes:
    - emptyDir: {}
      name: test-volume
  ...

The initContainer fails, because $(GIT_USERNAME) and $(GIT_PASSWORD) are used as is and not expanded. I have tried $GIT_USERNAME, ${GIT_USERNAME} and I am pretty much out of ideas.

How do I correctly use environment variables in args for init containers?

-- wederer
containers
docker
git
kubernetes
openshift

1 Answer

11/13/2018

Add environment variable in the init container.

spec:
  initContainers:
    - args:
        - clone
        - '--single-branch'
        - '--'
        - 'https://$(GIT_USERNAME):$(GIT_PASSWORD)@someurl.com/something.git'
        - '/testing/'
      image: alpine/git
      imagePullPolicy: Always
      name: init-clone-repo
      env:
        - name: GIT_USERNAME
          valueFrom:
            secretKeyRef:
              key: username
              name: git
        - name: GIT_PASSWORD
          valueFrom:
            secretKeyRef:
              key: password
              name: git
      resources: {}
      terminationMessagePath: /dev/termination-log
      terminationMessagePolicy: File
      volumeMounts:
        - mountPath: /testing
          name: test-volume
  volumes:
    - emptyDir: {}
      name: test-volume
-- nightfury1204
Source: StackOverflow