在本地主机而不是库存主机中运行 Ansible 任务

问题描述 投票:0回答:4

我需要检查本地主机上是否存在一个文件 (/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']

ansible ansible-2.x ansible-inventory
4个回答
3
投票

在本地主机测试路径时不需要模块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
    

0
投票
尝试以下操作:

--- - 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
 不同的机器上运行任务。


0
投票
尝试以下

--- - 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']
    

0
投票
感谢大家的大力支持。这是固定答案。

--- - 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']
    
© www.soinside.com 2019 - 2024. All rights reserved.