我正在使用嵌套字典,并且有多个具有相同键的字典文件。 字典和任务本身正在工作,但我需要添加以下条件。 如果子元素的状态==不存在,则不要运行任务
我的口述:
qualitygate:
- qualitygate_name: QA-dev
operators:
- metric: coverage
operator: CT
error: 1
state: present
- qualitygate_name: Department-xyc
operators:
- metric: coverage
operator: CT
error: 10
state: absent
- metric: duplicated_lines
operator: GT
error: 5
state: present
使用我的任务:
- ansible.builtin.uri:
url: "{{ protocol }}://{{ server_fqdn }}/api/qualitygates/create_condition"
user: "{{ token }}"
method: POST
body_format: form-urlencoded
body:
error: "{{ item.1.error }}"
metric: "{{ item.1.metric }}"
gateName: "{{ item.0.qualitygate_name }}"
op: "{{ item.1.operator }}"
loop: "{{ qualitygate | subelements('operators', 'skip_missing=True') }}"
when: qualitygate[item]['state'] is match("present")
如何更改过滤器以仅匹配值“present”
在条件中使用子元素项
when: item.1.state == 'present'
用于测试的完整剧本示例
- hosts: localhost
vars:
qualitygate:
- operators:
- {error: 1, metric: coverage, operator: CT, state: present}
qualitygate_name: QA-dev
- operators:
- {error: 10, metric: coverage, operator: CT, state: absent}
- {error: 5, metric: duplicated_lines, operator: GT, state: present}
qualitygate_name: Department-xyc
tasks:
- debug:
msg: |
error: {{ item.1.error }}
metric: {{ item.1.metric }}
op: {{ item.1.operator }}
gateName: {{ item.0.qualitygate_name }}
loop: "{{ qualitygate | subelements('operators', 'skip_missing=True') }}"
loop_control:
label: "{{ item.0.qualitygate_name }} {{ item.1.operator }} {{ item.1.state }}"
when: item.1.state == 'present'
给出了删节版
ok: [localhost] => (item=QA-dev CT present) =>
msg: |-
error: 1
metric: coverage
op: CT
gateName: QA-dev
skipping: [localhost] => (item=Department-xyc CT absent)
ok: [localhost] => (item=Department-xyc GT present) =>
msg: |-
error: 5
metric: duplicated_lines
op: GT
gateName: Department-xyc