使用ansible复制本地文件(如果存在)

时间:2015-03-04 13:03:13

标签: ansible ansible-playbook infrastructure

我正在项目中工作,我们使用ansible来创建部署服务器集群。 我要实现的任务之一是将本地文件复制到远程主机,只有当该文件存在于本地时。 现在我尝试使用此

解决此问题
- hosts: 127.0.0.1 
  connection: local
  tasks:
    - name: copy local filetocopy.zip to remote if exists
    - shell: if [[ -f "../filetocopy.zip" ]]; then /bin/true; else /bin/false; fi;
      register: result    
    - copy: src=../filetocopy.zip dest=/tmp/filetocopy.zip
      when: result|success

这是因为以下消息失败: 错误:'行动'或者' local_action'任务中缺少属性"将本地filetocopy.zip复制到远程(如果存在)"

我尝试使用命令任务创建此项。 我已经尝试使用local_action创建此任务,但我无法使其正常工作。 我发现的所有样本都没有将shell视为local_action,只有命令样本,并且它们都没有其他任何命令。 有没有办法使用ansible来完成这项任务?

5 个答案:

答案 0 :(得分:24)

更全面的答案:

如果您想在执行某项任务之前检查是否存在本地文件,请参阅以下全面的摘录:

- name: get file stat to be able to perform a check in the following task
  local_action: stat path=/path/to/file
  register: file

- name: copy file if it exists
  copy: src=/path/to/file dest=/destination/path
  when: file.stat.exists

如果您想在执行某项任务之前检查是否存在远程文件,可以采用以下方法:

- name: get file stat to be able to perform check in the following task
  stat: path=/path/to/file
  register: file

- name: copy file if it exists
  copy: src=/path/to/file dest=/destination/path
  when: file.stat.exists

答案 1 :(得分:21)

将您的第一步更改为以下

- name: copy local filetocopy.zip to remote if exists
  local_action: stat path="../filetocopy.zip"
  register: result    

答案 2 :(得分:5)

如果您不想设置两个任务,可以使用is_file检查本地文件是否存在:

tasks:
- copy: src=/a/b/filetocopy.zip dest=/tmp/filetocopy.zip
  when: '/a/b/filetocopy.zip' | is_file

该路径是相对于playbook目录的,因此如果您要引用角色目录中的文件,建议使用magic变量role_path。

参考:http://docs.ansible.com/ansible/latest/playbooks_tests.html#testing-paths

答案 3 :(得分:2)

Fileglob允许查找最终存在的文件。

- name: copy file if it exists
  copy: src="{{ item }}" dest=/destination/path
  with_fileglob: "/path/to/file"

答案 4 :(得分:-1)

这个怎么样?

tasks:
- copy: src=../filetocopy.zip dest=/tmp/filetocopy.zip
  failed_when: false

如果文件存在于本地,则会将文件复制到目标。如果它不存在,它就不会做任何事情,因为忽略了错误。

相关问题