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.
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.