Run Pod with unique POD name

12/28/2021

I have a script which execute on container and i use following command to create my container and exit once execution complete, this is working as per our requirement.

kubectl run -i tmp-pod --rm -n=mynamespace --image=placeholder --restart=Never --overrides="$(cat POD.json)"

it creates the pod and execute my script and terminate the pod itself once completed.

But my above kubectl command runs by many sources so if two source run same time then i get error Error from server (AlreadyExists): pods "POD_NAME" already exists

Is there anyway i can make my pod name unique so parallels run does not conflict with other pod?

here is my POD.json

{
	"apiVersion": "v1",
	"kind": "Pod",
	"metadata": {
		"name": "POD_NAME",
		 
	},
	"spec": {
		"restartPolicy": "Never",
		"containers": [
			{
				"name": "POD_NAME",
				"image": "my_IMAGE:2",
				"imagePullPolicy": "Always",
				"command": [
					"python",
					"/myscript.py",
					"INPUT_1",
					"INPUT_2"
				]
			}
		]
	}
}
-- user1591156
kubectl
kubernetes
kubernetes-pod

1 Answer

12/28/2021

In your case, as everything is the same, I suggest you run your pod something like this. As far as I know, k8s does not give you a build in solution for this.

kubectl run -i tmp-pod$((1 + $RANDOM % 1000000)) --rm -n=mynamespace --image=placeholder --restart=Never --overrides="$(cat POD.json)"

For documentation purpose, in case the POD.json has changing values: Using JQ, you can read the changing values in the POD.json like this

kubectl run -i tmp-pod$(cat POD.json | jq -r '.metadata.name') --rm -n=mynamespace --image=placeholder --restart=Never --overrides="$(cat POD.json)"

In case the value you are reading is not valid as pod name, you could also simply generate a md5sum based on the POD.json and use a part of that like this. Using cut, to shorten it.

kubectl run -i tmp-pod$(md5sum POD.json | cut -c1-10) --rm -n=mynamespace --image=placeholder --restart=Never --overrides="$(cat POD.json)"
-- Dennis van de Hoef
Source: StackOverflow