Search code examples
bashkubernetesyamlcommandkubernetes-pod

Kubernetes pod yaml: source command does not work


In the following pod yaml, I cannot get source command to work. Initially I inserted the command under args between echo starting and echo done and now I tried {.lifecycle.postStart} to no avail.

apiVersion: v1
kind: Pod
metadata:
  name: mubu62
  labels:
    app: mubu62
spec:
  containers:
  - name: mubu621
    image: dockreg:5000/mubu6:v6
    imagePullPolicy: Always
    ports:
    - containerPort: 5021
    command: ["/bin/sh","-c"]
    args: 
    - echo starting;
      echo CONT1=\"mubu621\" >> /etc/environment;
      touch /mubu621;
      sed -i 's/#Port 22/Port 5021/g' /etc/ssh/sshd_config;
      sleep 3650d;
      echo done;
    lifecycle:
      postStart:
        exec:
          command: ["/bin/bash","-c","source /etc/environment"]
  - name: mubu622
    image: dockreg:5000/mubu6:v6
    imagePullPolicy: Always
    ports:
    - containerPort: 5022
  imagePullSecrets:
  - name: regcred
  nodeName: spring
  restartPolicy: Always

Kubectl apply throws no errors, but echo $CONT1 returns nada! mubu6 is an ubuntu modified image.

The reason I am doing this, is because when I ssh from another pod in this pod (mubu621), Kubernetes environment variables set through env are not seen in the ssh session.

Any help would be much appreciated!


Solution

  • After experimenting with the suggestions under set-environment-variable-automatically-upon-ssh-login, what worked was to substitute

    echo CONT1=\"mubu621\" >> /etc/environment;
    

    with

    echo CONT1=\"mubu621\" >> /root/.bashrc;
    

    and delete

    lifecycle:
          postStart:
            exec:
              command: ["/bin/bash","-c","source /etc/environment"]
    

    that didn't work anyway.

    Upon SSH-ing from container mubu622 to container mubu621, I can now successfully execute echo $CONT1 with mubu621 output, without having to source /root/.bashrc first, which was initially the case with writing the env_variable in /etc/environment.

    In summary: when using a bash shell in kubernetes containers, you can SSH from another container and echo variables written in /root/.bashrc without sourcing (because kubernetes env_variables are not available in a ssh session). This is very useful e.g in the case of multi-container pods, so you know amongst other things in which container you are currently logged in.