我想运行一些Ansible命令,取决于基于存在的布尔值在我的任务中的条件检查的结果,并且试图将它绑定在结中工作。Ansible 2条件在循环中使用with_items
所需结果是如下,并且应该为每个项目hosts
阵列在运行:
- 检查是否
lynchburg
变量是true
或false
- 如果
lynchburg
变量是true
:- 设置文件夹结构如果它还不存在exis牛逼
- 创建一个从包含的模板文件
gulpfile.js
如果它不存在
- 如果
lynchburg
变量是false
:- 不要在安装文件夹结构
- 唐't创建
gulpfile.js
- Regar的
lynchburg
是否是true
或false
dless,跳过随后的reprovisions所有任务,作为文件夹结构和gulpfile.js
要么是有或没有(尽管这应该由逻辑在条件语句被照顾)
从下面包括了代码,我看到了以下结果:
- 当
lynchburg
是true
,提供贯穿预期 第一次就和任何后续reprovisions也作为 预期。 - 当
lynchburg
是false
,所述inc
文件夹结构是创建,然而gulpfile.js
不。
主循环任务运行的经过是这样的:
vhosts:
- site_name: sample
lynchburg: true
和任务如下:
# Create variable to check whether Lynchburg has already been installed
- name: Check if Lynchburg assets folders have been previously created
stat:
path: /var/www/{{ item.site_name }}/inc
with_items: "{{ vhosts }}"
when: item.lynchburg == true
register: lynchburg_assets
- name: Check if Lynchburg gulpfile.js has been previously created
stat:
path: /var/www/{{ item.site_name }}/gulpfile.js
with_items: "{{ vhosts }}"
when: item.lynchburg == true
register: lynchburg_gulpfile
- name: Create inc folder
with_items: "{{ lynchburg_assets.results }}"
file:
path: /var/www/{{ item.item.site_name }}/inc
state: directory
when: item.stat.isdir is undefined and item.item.lynchburg == true
- name: Create scss folder
with_items: "{{ lynchburg_assets.results }}"
file:
path: /var/www/{{ item.item.site_name }}/inc/scss
state: directory
when: item.stat.isdir is undefined and item.item.lynchburg == true
- name: Create js folder
with_items: "{{ lynchburg_assets.results }}"
file:
path: /var/www/{{ item.item.site_name }}/inc/js
state: directory
when: item.stat.isdir is undefined and item.item.lynchburg == true
- name: Create img folder
with_items: "{{ lynchburg_assets.results }}"
file:
path: /var/www/{{ item.item.site_name }}/inc/img
state: directory
when: item.stat.isdir is undefined and item.item.lynchburg == true
- name: Create fonts folder
with_items: "{{ lynchburg_assets.results }}"
file:
path: /var/www/{{ item.item.site_name }}/inc/fonts
state: directory
when: item.stat.isdir is undefined and item.item.lynchburg == true
- name: Create gulpfile.js
with_items: "{{ lynchburg_gulpfile.results }}"
template:
src: gulpfile.js
dest: /var/www/{{ item.item.site_name }}/gulpfile.js
when: item.stat.exists is defined and item.stat.exists == false and item.item.lynchburg == true
注:如果还有其他方法可以轻松创建完整的文件夹结构,而无需运行五个不同的任务 - 每个文件夹/子文件夹一个 - 并且有人可以建议这是什么,那也将被赞赏!
谢谢!我似乎已经解决了我的原始问题(请参阅我的评论),但是我在Ansible设置的另一个区域使用了您的解决方案,但由于完全相同的原因而导致出现问题,并且工作完美。 –
这是因为'defined/undefined'关键字有点脏处理(见[这里](https://github.com/ansible/ansible/blob/ff20ab7d4439ad6e5ca099c428ac6d3f25a154e7/lib/ansible/playbook/conditional.py#L211 ))。所以'dummy.key'在未定义的情况下会破坏jinja2表达式,而且语句的第二部分未经过测试。在定义/未定义之后,你实际上可能会写任何你想要的东西,比如:'when:dummy.key未定义,任何事情,你和想要的东西。为了克服这个问题,可以使用定义/未定义的测试作为最后一个测试,或者将其替换为默认值。 –