ansible verify the k8s deployment succeed

8/10/2020

I am using ansible k8s module to do the pod deployment, but unfortunately, I did not find a way to use wait and wait_condition correctly.

so I tried use the until and retry to implement another waiting

each time after you run the playbook, after you use k8s module to do the deployment, until NewReplicaSetAvailable shows up in the deployment within 2 minutes(60 * 2s), otherwise the deployment failed.

In case you need to verify the deployment result, I write down here.

    - name: Verify the deploy result
      shell: "kubectl -n kube-system get deployment coredns --output=jsonpath='{.status.conditions[*].reason}'"
      register: deploy_res
      until: "'NewReplicaSetAvailable' in deploy_res.stdout"
      retries: 60
      delay: 2
-- Z.Liu
ansible
kubectl
kubernetes

1 Answer

8/10/2020

the module k8s gives you not the status of the Deployment. For the status of a Deployment (or any other resource) you should use the module k8s_info. Then you can do your check on this task.

Example:

---
- hosts: localhost
  tasks:
  - name: Create a Service object from an inline definition
    k8s:
      state: present
      definition:
        apiVersion: v1
        kind: Deployment
        metadata:
          name: example
          namespace: default
        spec:
          replicas: 3
          selector:
            matchLabels:
              app: example-nginx
          template:
            metadata:
              labels:
                app: example-nginx
            spec:
              containers:
              - image: nginx
                name: nginx
  - name: check if deployment is ready
    k8s_info:
      kind: Deployment
      label_selectors: 
        - app = example-nginx
    register: output_info
    until: output_info.resources | json_query('[*].status.conditions[?reason==`NewReplicaSetAvailable`][].status') | select ('match','True') | list | length == 1
    delay: 2
    retries: 5

For the until filter there are certainly better solutions, but I have solved it this way for a similar use case. The until filter checks if there is a condition with the reason NewReplicaSetAvailable and it must be True. If that happens, the length is equal to 1

-- CLNRMN
Source: StackOverflow