【问题标题】:Ansible - Check if multiple files exists locally and copy to remoteAnsible - 检查本地是否存在多个文件并复制到远程
【发布时间】:2019-09-25 17:39:45
【问题描述】:

我是 Ansible 的新手,我正在尝试检查我的 Ansible 控制机器中是否存在文件(至少应该存在一个),如果存在,请复制到远程位置。

我想出了下面的方法,但是 ansible 正在检查远程而不是本地的文件。我也不确定如何使用“with_items”。

---
- hosts: linux
  gather_facts: no
  vars:
   source_dir: /login/my_home
   server_type: WRITEVIEW
   files:
      - app.xslt
      - Configuration.xml
      - fcCN.xslt

  tasks:
   - name: Validate if file exists
     local_action: file path="{{ source_dir }}/{{ item }}" state=file
     with_items: files

错误信息:

TASK [Validate if file exists] ****************************************************************************************************************************************** failed: [remoteserver_1 -> localhost] (item=files) => {"changed": false, "item": "files", "msg": "file (/login/my_home/files) is absent, cannot continue", "path": "/login/my_home/files", "state": "absent"} failed: [remoteserver_2 -> localhost] (item=files) => {"changed": false, "item": "files", "msg": "file (/login/my_home/files) is absent, cannot continue", "path": "/login/my_home/files", "state": "absent"}

【问题讨论】:

标签: ansible ansible-2.x


【解决方案1】:

您可以使用stat 命令来检查文件是否存在。如果存在,则copy它到远程服务器:

---
- hosts: linux
  gather_facts: no
  vars:
   source_dir: /login/my_home
   server_type: WRITEVIEW
   files:
      - app.xslt
      - Configuration.xml
      - fcCN.xslt

   tasks:
    - name: check if file exists
      local_action: stat path=/path/of/file/{{ item }}
      with_items: "{{ files }}"
      register: check_file_name

    - name: Verifying if file exists
      debug: msg="File {{ item.item }} exist"
      with_items: "{{ check_file_name.results }}"
      when: item.stat.exists

    - name: Copying the file
      copy: src=/path/of/file/local/{{ item.item }} dest=/path/of/file/remote/
      with_items: "{{ check_file_name.results }}"
      when: item.stat.exists

【讨论】:

  • 非常感谢,不过只是一个小小的说明。调试: msg="File {{ item.item }} 存在" - 为什么 item.item 而不是只有 item ?
  • @Rookie1999 item.item 用于获取用于在第一个任务中循环的实际项目。在这种情况下,它的文件名。见这里:docs.ansible.com/ansible/latest/user_guide/…
猜你喜欢
  • 1970-01-01
  • 2020-07-27
  • 2020-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-15
相关资源
最近更新 更多