如果存在stat结果,则向执行任务的items注册stat结果



我是ansible的新手,已经用完了论坛搜索。我似乎找不到关于with_itemswhen的这个问题的答案现在的剧本将运行,但对于该机器上不存在的列表中的每个路径,它都会导致失败消息"src file not exists"。

由于这是在几台机器上运行的,所以有很多失败的(红色(消息毫无意义。我认为when语句只会在statresult存在的情况下运行任务。事实并非如此。

基本上,我要做的是检查几台机器,看看这两条路径是否存在。如果是,请为每个符号创建一个符号链接。所有要签入的路径都不同。现在我有:

---
- hosts: all
become: yes
gather_facts: no
tasks:
- name: Check that domains exist
stat:
path: '/path/to/the/domain/{{ item.domainpath }}'
get_attributes: no
get_checksum: no
get_md5: no
get_mime: no
register: item.statresult
with_items:
- { domainpath: 'path1/', statresult: 'stat_result_path1' }
- { domainpath: 'path2/', statresult: 'stat_result_path2' }
- { domainpath: 'path3/', statresult: 'stat_result_path3' }
- name: Create symlink for bin on existing domain machines
file:
src: '/path/to/the/domain/{{ item.srcbin }}'
dest: /path/new/symlink_bin_link
state: link
with_items:
- { srcbin: 'path1/bin/', domainexists: 'stat_result_path1.stat.exists' }
- { srcbin: 'path2/bin/', domainexists: 'stat_result_path2.stat.exists' }
- { srcbin: 'path3/bin/', domainexists: 'stat_result_path3.stat.exists' }
when: item.domainexists
ignore_errors: yes
- name: Create symlink for config on existing domain machines
file:
src: '/path/to/the/domain/{{ item.srcconfig }}'
dest: /path/new/symlink_config_link
state: link
with_items:
- { srcconfig: 'path1/config/', domainexists: 'stat_result_path1.stat.exists' }
- { srcconfig: 'path2/config/', domainexists: 'stat_result_path2.stat.exists' }
- { srcconfig: 'path3/config/', domainexists: 'stat_result_path3.stat.exists' }
when: item.domainexists
ignore_errors: yes

我必须使用ignore_errors,否则它将不会进入第二个任务。我尝试过使用when: item.domainexists == true,但这会导致任务被跳过,即使它与现有路径匹配。

即使when语句在每个with_items上迭代,也应该无关紧要,因为只要它匹配一个,它就应该正确地执行任务?

这就是你的剧本应该是什么样子的:

---
- hosts: all
become: yes
gather_facts: no
tasks:
- name: Check that domains exist
stat:
path: /path/to/the/domain/{{ item }}
loop:
- path1
- path2
- path3
register: my_stat
- name: Ensure symlinks are created for bin on existing domain machines
file:
src: /path/new/symlink_bin_link
dest: /path/to/the/domain/{{ item }}/bin
state: link
loop: "{{ my_stat.results | selectattr('stat.exists') | map(attribute='item') | list }}"
- name: Ensure symlinks are created for config on existing domain machines
file:
src: /path/new/symlink_config_link
dest: /path/to/the/domain/{{ item }}/config
state: link
loop: "{{ my_stat.results | selectattr('stat.exists') | map(attribute='item') | list }}"

说明:

  • register: item.statresult在Ansible中是一个无意义的构造,您应该提供一个变量的名称作为参数

  • 该变量将包含在循环中运行的任何任务的结果列表

  • 您应该处理该列表(请参阅此答案以了解selectattrmap(,以获得(仅(存在的路径列表

  • 你应该循环浏览经过过滤和映射的列表

此外:对于符号链接,srcdest的定义方式应与代码中的定义方式相反。


此外,您可以通过在可迭代定义中添加product过滤器,将最后两个任务合并为一个任务。

最新更新