kubernetesyamlargo-workflowsargo

How to pass environment variables to a script present in ConfigMap while accessing it as a volume in Kubernetes


I have the following ConfigMap which is having a variable called VAR. This variable should get the value from the workflow while accessing it as a volume

apiVersion: v1
kind: ConfigMap
metadata:
  name: test-pod-cfg
data:
  test-pod.yaml: |-
    apiVersion: v1
    kind: Pod
    metadata:
      name: test-pod
    spec:
      containers:
        - name: test
          image: ubuntu
          command: ["/busybox/sh", "-c", "echo $VAR"]

Here is the argo workflow which is fetching script test-pod.yaml in ConfigMap and adding it as a volume to container. In this how to pass Environment variable VAR to the ConfigMap for replacing it dynamically

apiVersion: argoproj.io/v1alpha1
kind: Workflow
metadata:
  name: test-wf-
spec:
  entrypoint: main
  templates:
    - name: main
      container:
        image: "ubuntu"
        command: ["/bin/sh", "-c", "cat /mnt/vc/test"]
        volumeMounts:
          - name: vc
            mountPath: "/mnt/vc"
      volumes:
        - name: vc
          configMap:
            name: test-pod-cfg
            items:
              - key: test-pod.yaml
                path: test

Solution

  • To mount the ConfigMap as a volume and make the environment variable VAR available to the container, you will need to add a volume to the pod's spec and set the environment variable in the container's spec.

    In the volume spec, you will need to add the ConfigMap as a volume source and set the path to the file containing the environment variable. For example:

    spec:
      entrypoint: test-pod
      templates:
      - name: test-pod
        container:
          image: ubuntu
          command: ["/busybox/sh", "-c", "echo $VAR"]
          volumeMounts:
          - name: config
            mountPath: /etc/config
          env:
          - name: VAR
            valueFrom:
              configMapKeyRef:
                name: test-pod-cfg
                key: test-pod.yaml
        volumes:
        - name: config
          configMap:
            name: test-pod-cfg
    

    The environment variable VAR will then be available in the container with the value specified in the ConfigMap.

    For more information follow this official doc.