Ansible: apply when to complete loop

 ̄綄美尐妖づ 提交于 2020-01-07 07:25:40

问题


I want to combine a loop in ansible with a when-statement applied to it. When-statements are applied to each loop iteration however, which takes away the possibility to apply one to the complete loop. Does anyone know how to do this?

I've run into this problem before, but in this specific case it concerns a variable that might or might not exist. What I would want to do is something like:

- name: Loop
  debug:
    msg: "{{ item }}"
  with_items: x.y|default([])
  but-only-run-this-loop-when: x is defined

The default-filter takes care of those instances where y is not defined. Since in my case x might als be not defined, I need the but-only-run-this-loop-when. Obviously, this is not a real ansible statement. What should I use in stead?

Currently, I use something horrible like:

- name: kludge1
  set_fact:
    fake_y : "{{ [] }}"

- name: kludge2
  set_fact:
    fake_y : "{{ x.y|default([]) }}"
  when: x is defined

- name: Loop
  debug:
    msg: "{{ item }}"
  with_items: '{{ fake_y }}'

With for example in host_vars:

x:
  y:
    - "foo"
    - "bar"

But I'm sure that's not the way to go.


回答1:


There's similar answer here. You can use several defaults in a row:

- name: Loop
  debug:
    msg: "{{ item }}"
  with_items: (x | default({})).y | default([])

And there is no way to bound when statement to looped task as a whole (at least in current Ansible 2.2).



来源:https://stackoverflow.com/questions/42491293/ansible-apply-when-to-complete-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!