Search code examples
kuberneteskubectl

Create multiple pods from the same YAML definition file


So, I have a pod definition file and I was wondering if there was a way to use the kubectl apply command to create multiple instances of the pod from the same definition file. I know this can be done with a deployment but wondering if there was a way to quickly spin up multiple pods using the apply command?


Solution

  • I know this can be done with a deployment but wondering if there was a way to quickly spin up multiple pods using the apply command?

    Yes, this is possible but not with the simple kubectl apply command as it doesn't have such options/capabilities and cannot be used to create multiple instances of a pod from a single yaml definition file.

    If you just need to create n number of independent pods, not managed by any replicaset, deployment, statefulset etc., you can use for this purpose a simple bash one-liner.

    Suppose we want to quickly spin up 10 independent pods based on the following yaml template, named pod-template.yaml:

    apiVersion: v1
    kind: Pod
    metadata:
      name: {{pod-name}}
    spec:
      containers:
        - name: web
          image: nginx
          ports:
            - name: web
              containerPort: 80
              protocol: TCP
    

    We can do it with the following script:

    for i in {1..10}; do sed "s/{{pod-name}}/pod-$i/g" pod-template.yaml | kubectl apply -f - ; done
    

    It will create 10 pods named pod-1, pod-2 ... pod-10:

    $ for i in {1..10}; do sed "s/{{pod-name}}/pod-$i/g" pod-template.yaml | kubectl apply -f - ; done
    pod/pod-1 created
    pod/pod-2 created
    pod/pod-3 created
    pod/pod-4 created
    pod/pod-5 created
    pod/pod-6 created
    pod/pod-7 created
    pod/pod-8 created
    pod/pod-9 created
    pod/pod-10 created
    

    And just in case you want to delete them now and don't want to do it one by one ;)

    for i in {1..10};do kubectl delete pod pod-$i; done