Home > Net >  Env var not available in scipt/command in a kind Job (Kubernetes)
Env var not available in scipt/command in a kind Job (Kubernetes)

Time:04-20

I run this Job:

kubectl apply -f - <<EOF
apiVersion: batch/v1
kind: Job
metadata:
  name: sample
spec:
  template:
    spec:
      containers:
      - command:
        - /bin/bash
        - -c
        - |
          env
          echo "MY_VAR : ${MY_VAR}"
          sleep 800000
        env:
        - name: MY_VAR
          value: MY_VALUE
        image: mcr.microsoft.com/azure-cli:2.0.80
        imagePullPolicy: IfNotPresent
        name: sample
      restartPolicy: Never
  backoffLimit: 4
EOF

But when I look at the log the value MY_VALUE its empty even though env prints it:

$ kubectl logs -f sample-7p6bp
...
MY_VAR=MY_VALUE
...
MY_VAR : 

Why does this line contain an empty value for ${MY_VAR}:

echo "MY_VAR : ${MY_VAR}"

?

UPDATE: Tried the same with a simple pod:

kubectl -f - <<EOF
apiVersion: v1
kind: Pod
metadata:
  name: sample
spec:
  containers:
  - name: sample
    imagePullPolicy: Always
    command: ["/bin/sh", "-c", "echo BEGIN ${MY_VAR} END"]
    image: radial/busyboxplus:curl
    env:
    - name: MY_VAR
      value: MY_VALUE
EOF

Same/empty result:

$ kubectl logs -f sample
BEGIN END

CodePudding user response:

The reason this happens is because your shell expands the variable ${MY_VAR} before it's ever sent to the kubernetes. You can disable parameter expansion inside of a heredoc by quoting the terminator:

kubectl apply -f - <<'EOF'

Adding these quotes should resolve your issue.

  • Related