How to use heredoc to create a yaml file in k8s pod yaml definition?

10/23/2021

I would like to create a yaml once the k8s pod is up, in my previous attempt, I just upload the yaml file and use wget to download it.

apiVersion: v1
kind: Pod
metadata:
  name: test
spec:
  containers:
    - name: p-test
      image: p-test:latest
      command:
        - sh
        - '-c'
        - >-
          wgethttps://ppt.cc/aId -O labels.yml
      image: test/alpine-utils

In order to make it more explicit, I try to use heredoc to embed the content of labels.yml into the k8s pod manifest, like:

apiVersion: v1
kind: Pod
metadata:
  name: test
spec:
  containers:
    - name: p-test
      image: p-test:latest
      command:
        - "/bin/bash"
        - '-c'
        - > 
          cat << LABEL > labels.yml

	      key: value

          LABEL

But it doesn't work, please suggest how to modify it, thanks.

-- good5dog5
heredoc
kubernetes
yaml

1 Answer

10/27/2021

Instead of playing with heredoc in pod definition, it's much better and convenient to define your yaml file in the ConfigMap and refer to it in your pod definition (mount it as volume and use subPath) - like in this example (I changed p-test image into nginx image):

apiVersion: v1
kind: ConfigMap
metadata:
  name: my-configmap
data:
  labels.yaml: |-
    key: value
---
apiVersion: v1
kind: Pod
metadata:
  name: test
spec:
  containers:
    - name: p-test
      image: nginx:latest
      volumeMounts:
      - name: my-configmap-volume
        mountPath: /tmp/labels.yaml
        subPath: labels.yaml
  volumes:
  - name: my-configmap-volume
    configMap:
      name: my-configmap

Then on the pod you will find your labels.yaml in the /tmp/labels.yaml.

-- Mikolaj S.
Source: StackOverflow