Home > database >  Using Ansible json_query to Check Output of Json Kubectl command
Using Ansible json_query to Check Output of Json Kubectl command

Time:12-15

I am trying to use Ansible to put a pause in my playbook, since I am installing an operator from the Operator Hub and don't want to continue, until I know the CRDs I require in the following steps are installed. I have the following task but can't get it working yet.

- name: Wait for CRDs to be available
  command: kubectl get sub my-operator -n openshift-operators -o json
  register: cmd
  retries: 10
  delay: 5
  until: cmd.stdout | json_query('status.conditions[0].status') == true

Sample JSON

{
  "apiVersion": "operators.coreos.com/v1alpha1",
  "kind": "Subscription",
  "metadata": {
    "creationTimestamp": "2021-12-13T04:23:58Z",
    "generation": 1,
    "labels": {
      "operators.coreos.com/argocd-operator.openshift-operators": ""
    },
    "name": "argocd-operator",
    "namespace": "openshift-operators",
    "resourceVersion": "58122",
    "uid": "6eaad3c1-8329-4d00-90b8-1ab635b3b370"
  },
  "spec": {
    "channel": "alpha",
    "config": {
      "env": [
        {
          "name": "ARGOCD_CLUSTER_CONFIG_NAMESPACES",
          "value": "argocd"
        }
      ]
    },
    "installPlanApproval": "Automatic",
    "name": "argocd-operator",
    "source": "community-operators",
    "sourceNamespace": "openshift-marketplace",
    "startingCSV": "argocd-operator.v0.1.0"
  },
  "status": {
    "catalogHealth": [
      {
        "catalogSourceRef": {
          "apiVersion": "operators.coreos.com/v1alpha1",
          "kind": "CatalogSource",
          "name": "operatorhubio-catalog",
          "namespace": "olm",
          "resourceVersion": "57924",
          "uid": "95871859-edbc-45ad-885c-3edaad2a1df6"
        },
        "healthy": true,
        "lastUpdated": "2021-12-13T04:23:59Z"
      }
    ],
    "conditions": [
      {
        "lastTransitionTime": "2021-12-13T04:23:59Z",
        "message": "targeted catalogsource openshift-marketplace/community-operators missing",
        "reason": "UnhealthyCatalogSourceFound",
        "status": "True",
        "type": "CatalogSourcesUnhealthy"
      }
    ],
    "lastUpdated": "2021-12-13T04:23:59Z"
  }
}

CodePudding user response:

There is a small detail that is tripping up the condition. In the JSON output, the status is a string "True" and not a boolean which we are comparing.

Note: "status": "True"

Changing the condition to match the string True...

until: cmd.stdout | json_query('status.conditions[0].status') == "True"

Or, applying the | bool filter...

until: stdout | json_query('status.conditions[0].status') | bool

The complete task:

- name: Wait for CRDs to be available
  command: kubectl get sub my-operator -n openshift-operators -o json
  register: cmd
  retries: 10
  delay: 5
  until: cmd.stdout | json_query('status.conditions[0].status') | bool
  • Related