如何为整个项目而不是单个项目创造条件 [英] How to have a condition for with-items as a whole, not for the individual items
本文介绍了如何为整个项目而不是单个项目创造条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个:
- 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)
我得到的
'dict object' has no attribute u'blah'
如果when条件为false,我需要跳过整个任务.
What I need is to skip the whole task if the when condition is false.
推荐答案
使用with_items
时,无法将when
条件附加到整个任务上.
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([]) }}"
在这种情况下,如果您提供未知的服务名称,则该任务将有零个要重复的项目.
还要注意,我在您的with_items
结构中删除了不必要的列表定义.
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.
这篇关于如何为整个项目而不是单个项目创造条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文