我需要检查本地主机上是否存在一个文件 (/tmp/test.html),如果存在则执行其他任务。 你能帮忙在本地主机(工作站)中运行第一个任务(名称:检查存在和复制)吗?
localhost:工作站 远程主机:servera、serverb
下面是我的剧本.yml
---
- name: Check exist and copy
hosts: all
tasks:
- name: check if file is exists #need to execute this task in workstation
stat:
path: /tmp/test.html
register: file_present
- name: copy to taggroup 1
copy:
src: /tmp/test.html
dest: /tmp/dest1.html
when: file_present.stat.exists == 0 and inventory_hostname in groups ['taggroup1']
- name: copy to taggroup 2
copy:
src: /tmp/test.html
dest: /tmp/dest2.html
when: file_present.stat.exists == 0 and inventory_hostname in groups ['taggroup2']
在本地主机测试路径时不需要模块stat。例如,如果文件 /tmp/test.html 不存在,则播放失败,否则继续播放。
- hosts: all
vars:
my_file: '/tmp/test.html'
tasks:
- fail:
msg: "{{ my_file }} does not exist. End of play."
when: my_file is not exists
delegate_to: localhost
run_once: true
- debug:
msg: "Continue play."
run_once: true
---
- name: Check exist and copy
hosts: all
tasks:
- name: check if file is exists #need to execute this task in workstation
stat:
path: /tmp/test.html
register: file_present
delegate_to: localhost
- name: copy to taggroup 1
copy:
src: /tmp/test.html
dest: /tmp/dest1.html
when: file_present.stat.exists and inventory_hostname in groups ['taggroup1']
- name: copy to taggroup 2
copy:
src: /tmp/test.html
dest: /tmp/dest2.html
when: file_present.stat.exists and inventory_hostname in groups ['taggroup2']
见
文档.
您可以使用delegate_to:
在与当前
ansible_host
不同的机器上运行任务。
---
- name: Check exist and copy
hosts: all
tasks:
- name: check if file is exists #need to execute this task in workstation
stat: path=/tmp/test.html
register: file_present
delegate_to: localhost
- name: copy to taggroup 1
copy:
src: /tmp/test.html
dest: /tmp/dest1.html
when: file_present.stat.exists and inventory_hostname in groups ['taggroup1']
- name: copy to taggroup 2
copy:
src: /tmp/test.html
dest: /tmp/dest2.html
when: file_present.stat.exists and inventory_hostname in groups ['taggroup2']
---
- name: Check exist and copy
hosts: all
tasks:
- name: check if file is exists #need to execute this task in workstation
stat:
path: /tmp/test.html
register: file_present
delegate_to: localhost
run_once_ true
- name: copy to taggroup 1
copy:
src: /tmp/test.html
dest: /tmp/dest1.html
when: file_present.stat.exists and inventory_hostname in groups ['taggroup1']
- name: copy to taggroup 2
copy:
src: /tmp/test.html
dest: /tmp/dest2.html
when: file_present.stat.exists and inventory_hostname in groups ['taggroup2']