【发布时间】:2021-04-02 19:58:05
【问题描述】:
我有一些涉及 json_query 的 ansible 代码在我试图使其成为条件的循环中。但我认为对于 when 子句和循环,我有些不理解。
下面的代码工作正常,当条件满足时(IaC.status == 400),问题是当条件不满足时,第二个任务仍然运行,循环尝试处理IaC2,它没有' t 存在,并且任务失败:"Invalid data passed to 'loop', it requires a list, got this instead:
我认为这实际上是条件语句和循环的预期行为:(https://docs.ansible.com/ansible/latest/user_guide/playbooks_conditionals.html#using-conditionals-in-loops),但描述的跳过整个任务的解决方案是使用空迭代器,但我不知道如何将它与json_query() 语句。
有谁知道我如何才能真正使下面的第二个任务有条件?
# The preceding code has made a RESTful API call to create a gitlab group, if the group
# exists the return status is 400, so I need to look it up instead. In which case the
# following code works fine. The problem is when IaC.status = 201 for some reason the loop
# in the 2nd task below tries to run, despite the when clause, and fails
# because the variable IaC2 doesn't exist
- name: or if IaC already exists
when: IaC.status == 400
uri:
url: https://{{new_hostname}}/api/v4/groups
method: GET
headers:
Authorization: "Bearer {{token.json.access_token}}"
body_format: json
body:
name: "IaC"
top_level_only: true
status_code: 200
validate_certs: yes
register: IaC2
- name: json_query to find the IaC group id when status = "{{IaC.status}}"
when: IaC.status == 400
debug:
var: item
loop: "{{ IaC2 | community.general.json_query(jmesquery) }}"
vars:
jmesquery: "json[?name=='IaC'].id"
register: group_id
【问题讨论】:
-
无论何时条件是什么,您的循环子句都将始终被解释。此外,即使总是错误的,每次迭代都会测试条件。我怀疑 IaC2 不存在,因为它是一个寄存器。虽然它可能是空的(调试会非常有帮助)。您可以通过在 IaC2 为空或为空时为其分配一个默认的空列表值 (
[]) 来解决此问题,以便您的循环表达式返回一个空列表。请参阅default过滤器及其第二个可选参数 (true)
标签: json loops ansible conditional-statements