如何在Ansible中用when条件实现本地存在指定文件夹才复制到目标服务器
解决Ansible根据本地文件夹存在性复制文件的问题
方法一:通过循环索引匹配检查结果
直接利用注册变量的结果列表索引与复制任务循环索引的对应关系,设置when条件:
--- - hosts: all gather_facts: true vars: domains: - domain: domain1.com - domain: domain2.com - domain: domain3.com tasks: - name: 检查本地网站文件是否存在 local_action: stat path={{ playbook_dir }}/files/var/www/{{ item.domain }} register: files_check with_items: "{{ domains }}" - name: 复制自定义文件(仅当本地文件夹存在时) copy: src: files/var/www/{{ item.domain }} dest: /var/www/{{ item.domain }} owner: root group: root force: true with_items: "{{ domains }}" when: files_check.results[ansible_loop.index0].stat.exists
说明
files_check.results是检查任务返回的结果列表,每个元素对应domains列表中的一个域名项ansible_loop.index0是当前循环的索引(从0开始),用于匹配结果列表中对应的检查记录stat.exists字段标记该域名对应的本地文件夹是否存在,值为true时执行复制操作
方法二:整理为字典(逻辑更直观)
先将检查结果整理为以域名为键的字典,再在复制任务中直接引用:
--- - hosts: all gather_facts: true vars: domains: - domain: domain1.com - domain: domain2.com - domain: domain3.com tasks: - name: 检查本地网站文件是否存在 local_action: stat path={{ playbook_dir }}/files/var/www/{{ item.domain }} register: files_check with_items: "{{ domains }}" - name: 整理域名存在性字典 set_fact: domain_exists: "{{ domain_exists | default({}) | combine({ item.item.domain: item.stat.exists }) }}" with_items: "{{ files_check.results }}" - name: 复制自定义文件(仅当本地文件夹存在时) copy: src: files/var/www/{{ item.domain }} dest: /var/www/{{ item.domain }} owner: root group: root force: true with_items: "{{ domains }}" when: domain_exists[item.domain]
说明
set_fact任务将每个域名的检查结果合并到domain_exists字典中,键为域名,值为布尔值(标记文件夹是否存在)- 复制任务的
when条件直接通过域名从字典中获取状态,逻辑清晰,不受循环顺序影响
内容的提问来源于stack exchange,提问作者Amin Persia
相关产品推荐
相关产品推荐

