首页 > 解决方案 > Ansible 命令从远程服务器中提取文件并阻止(如果已经存在)

问题描述

使用 Ansible 托管服务器(172.19.113.104) 我想从远程服务器(172.19.113.87)复制文件(ansibletestMariaDB-client-5.1.67-122.el5.x86_64.rpm),但如果文件已经存在。

我尝试如下但抛出错误:

- hosts: webservers
  vars:
   ip: 172.19.113.87
  tasks:
  - name: this is to pull
    local_action: shell 'ls /opt/ansibletest'
    register: result

  - name: ts2
    synchronize:  src={{ item }} dest=/opt/ mode=pull
    with_items:
    - "/opt/ansibletest"
    - "/opt/MariaDB-client-5.1.67-122.el5.x86_64.rpm"
    when: result.shell.exists == true









[root@rbtstaging ansible]# ansible-playbook fetch.yml

PLAY [webservers] ************************************************************************************************************************************************

TASK [Gathering Facts] *******************************************************************************************************************************************
ok: [172.19.113.87]

TASK [this is to pull] *******************************************************************************************************************************************
changed: [172.19.113.87]

TASK [ts2] *******************************************************************************************************************************************************
fatal: [172.19.113.87]: FAILED! => {"msg": "The conditional check 'result.stat.exists == True' failed. The error was: error while evaluating conditional (result.stat.exists == True): 'dict object' has no attribute 'stat'\n\nThe error appears to have been in '/RND/sudhir/ansible/fetch.yml': line 9, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n  - name: ts2\n    ^ here\n"}
    to retry, use: --limit @/RND/sudhir/ansible/fetch.retry

PLAY RECAP *******************************************************************************************************************************************************
172.19.113.87              : ok=2    changed=1    unreachable=0    failed=1   

注意:文件存在权限

标签: ansible

解决方案


您可以通过本地“stat”操作预先获取(从远程服务器获取文件 - 副本会将文件发送到删除服务器),并检查本地文件是否存在。

local_action:
  module: stat
  path: /path/to/local/file
register: local_file
become: no

fetch:
  src: /path/to/remote/file
  dest: /path/to/local/file
  flat: yes
when: local_file.stat.exists == False

推荐阅读