How to have a condition for with-items as a whole,

2019-08-03 08:52发布

问题:

I have this:

- name: Add hosts to /etc/hosts
  lineinfile:
    dest=/etc/hosts
    line='{{ item.dest }} {{ item.src }}'
    regexp='.*{{ item.src }}.*'
    state=present
  with_items:
    - "{{ hosts[service_name] }}"
  when: (service_name in hosts)

What I get

'dict object' has no attribute u'blah'

What I need is to skip the whole task if the when condition is false.

回答1:

There is no way to attach when condition to a whole task when using with_items.

But you can go another way – default iterator to empty list if there is no key, like this:

- name: Add hosts to /etc/hosts
  lineinfile:
    dest=/etc/hosts
    line='{{ item.dest }} {{ item.src }}'
    regexp='.*{{ item.src }}.*'
    state=present
  with_items: "{{ hosts[service_name] | default([]) }}"

In this case the task will have zero items to iterate over if you provide unknown service name.
Also note that I removed unnecessary list definition in your with_items construction.



标签: ansible