使用 Ansible json_query 检查 Json Kubectl 命令的输出

Using Ansible json_query to Check Output of Json Kubectl command

我正在尝试使用 Ansible 暂停我的剧本,因为我正在从 Operator Hub 安装一个 Operator 并且不想继续,直到我知道我在以下步骤中需要的 CRD 已安装.我有以下任务,但还不能让它工作。

- 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

样本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"
  }
}

有一个小细节导致了这种情况。在 JSON 输出中,状态是一个字符串 "True" 而不是我们正在比较的布尔值。

注:"status": "True"

正在更改条件以匹配字符串 True...

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

或者,应用 | bool 过滤器...

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

完成任务:

- 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