Kubernetes: Let a Pod Creates Another Pod
This is a quick tutorial to enable a k8s pod to create another pod within the same cluster. The steps below will be the same to create any k8s object from a Pod.
Step 1: Creating a service-account to privilege a pod to create another k8s object within the same cluster.
kubectl create sa pod-enabler
Step 2: Empowering the service-account with required permissions.
Note 1: A service-account without any role/rolebinding can do almost nothing in k8s.
Note 2: In this tutorial, the service-account is granted with cluster-level administration permission as below to make it short. Ideally, we need to create a role with only required permissions and bind the service-account accordingly.
kubectl create rolebinding pod-enabler-rb --clusterrole=cluster-admin --serviceaccount=default:pod-enabler
Step 3: Creating a configmap definition (payload.yaml) to create and mount a shell script file within a pod
The shell script is to connect the apiserver and create a k8s object (a pod is created in this example).
Note 1: ‘/var/run/secrets/kubernetes.io/serviceaccount’ is the location where the service token and CA cert will be exposed at by default automatically.
Note 2: When a service-account is configured in the pod definition file (as you can see in the pod definition below for instance), its token will be exposed at /var/run/secrets/kubernetes.io/serviceaccount/token. It will be the default token otherwise.
Note 3: The curl command in the script posts a pod definition as a json payload to apiserver.
Step 4: Creating the pod definition (podcreator.yaml) which will create another pod
Note 1: The shell script created via configmap is mounted as file in /data directory.
Note 2: ‘command: [“/bin/sh”, “-c”, “sh /data/pod-definition.sh”]’ triggers the script which will create a new pod in the same cluster.
Step 5: Creating the configmap and the pod
kubectl create -f payload.yaml
kubectl create -f podcreator.yaml
Note 1: The configmap should be created first and then the pod.
Note 2: Once the both objects are created, you can list the pods and see there would be a new pod with the name ‘new-nginx’.