Add random string on Kubernetes pod deployment name

12/29/2017

I have a template that is basically an utility container for running kubectl inside a pod.

What I want to do, is to be able to have multiple deployments of that same template, with different names, as in "utilitypod-randomID".

Is there a way to do that, via kubectl and some shell scripting, or something similar?

The current template looks like this:

apiVersion: v1
kind: Pod
metadata:
  name: utilitypod
  namespace: blah-dev
labels:
  purpose: utility-pod
spec:
  containers:
  - name: utilitypod
  image: blahblah/utilitypod:latest
  command: [ "/bin/bash", "-c", "--" ]
  args: [ "while true; do sleep 28800; done;" ]
  env: 
  - name: KUBERNETES_SERVICE_HOST
    value: "api.dev.blah.internal"
  - name: KUBERNETES_SERVICE_PORT
    value: "443"
--
kubectl
kubernetes

1 Answer

12/29/2017

You can replace name with generateName, which adds a random suffix. Your template will look like this:

apiVersion: v1
kind: Pod
metadata:
  generateName: utilitypod-
  namespace: blah-dev
labels:
  purpose: utility-pod
spec:
  containers:
  - name: utilitypod
  image: blahblah/utilitypod:latest
  command: [ "/bin/bash", "-c", "--" ]
  args: [ "while true; do sleep 28800; done;" ]
  env: 
  - name: KUBERNETES_SERVICE_HOST
    value: "api.dev.blah.internal"
  - name: KUBERNETES_SERVICE_PORT
    value: "443"

Mind you, this will only work with kubectl create -f template.yaml, not apply, as apply looks for a resource by its name and tries to compare their definitions, but this template doesn't contain a specific name.

-- Robert Lacok
Source: StackOverflow