【发布时间】:2020-10-07 08:27:01
【问题描述】:
我尝试将输出注册到一个变量,但我无法按照我想要的方式过滤。
输出:
oc get hpa -o json |jq -r '.items[].spec'
{
"maxReplicas": 3,
"minReplicas": 1,
"scaleTargetRef": {
"apiVersion": "apps.openshift.io/v1",
"kind": "DeploymentConfig",
"name": "hello-openshift"
},
"targetCPUUtilizationPercentage": 70
}
{
"maxReplicas": 4,
"minReplicas": 2,
"scaleTargetRef": {
"apiVersion": "apps/v1",
"kind": "Deployment",
"name": "testrhel"
},
"targetCPUUtilizationPercentage": 79
}
将输出注册到变量
- name: check for existing
shell: oc get hpa -o json |jq -r '.items[].spec'
register: existing
我想循环 output.name 并将其与另一个变量进行比较。
- name: set_fact
exist: {% if item.name == newvar and item.kind == newvar2 %}yes{%else%}no{%endif%}
loop:
- "{{ existing }}"
- name: task
shell: do something
when: exist == yes
提前致谢。
编辑: 目前我正在使用下面来比较变量。
- name: Get existing hpa output
shell: oc get hpa -o json -n {{ namespace }} |jq -r '.'
register: tempvar
- name: set hpa variable to fact
set_fact:
existing_deploy: "{{ tempvar.stdout}}"
- name: Comparing existing hpa to new config
set_fact:
hpa_exist: "{% if deploy_type == item.spec.scaleTargetRef.kind|lower and deploy_name == item.spec.scaleTargetRef.name|lower %}yes{% else %}no{% endif %}"
with_items:
- "{{ existing_deploy['items'] }}"
但是当我尝试使用条件时变量被覆盖
- name: task a
include_tasks: a.yml
when: hpa_exist
- name: task b
include_tasks: b.yml
when: not hpa_exist
deploymentconfig/hello-openshift 条件总是失败,即使它是真的。导致执行任务 b,这是不应该的
【问题讨论】:
-
您是否调试了
existing的内容以查看其确切的结构/内容,然后尝试相应地使用它?提示:由于您是从 shell 注册的,它将包含一个existing.stdout条目,其中可能包含您要查找的确切数据。提示 2:ansible 有一个from_json过滤器来解析 json 的文本表示。提示 3:您的实际输出不是有效的 json。