Making kubectl apply command idempotent in ansible

1/14/2020

I want to provision a cluster via successive resource application within a cluster.

At some point in time, I want to apply an nginx deployment, the one suited for the creation of nginx - based ingresses, so I want to run the following command in a shell:

kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/nginx-0.27.0/deploy/static/mandatory.yaml

My question is how can I make this idempotent, i.e. not to fail when the resources exist.

Is the k8s ansible module suited for this?

-- pkaramol
ansible
kubernetes

2 Answers

1/14/2020

kubectl apply won't throw an error if the resource already exists. It is suited for your need. kubectl create will throw error if resource exists.

-- Shashank V
Source: StackOverflow

1/14/2020

@Shashank V is right in his answer but I would like to expand it a bit with a help from the official documentations.

Apply manages applications through files defining Kubernetes resources. It creates and updates resources in a cluster through running kubectl apply. This is the recommended way of managing Kubernetes applications on production. See Kubectl Book.

Definition, usage and flags can be found here:

Apply a configuration to a resource by filename or stdin. The resource name must be specified. This resource will be created if it doesn't exist yet. To use apply, always create the resource initially with either apply or create --save-config.

I hope it makes the topic clearer.

-- OhHiMark
Source: StackOverflow