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

dir*_*ini 23 infrastructure ansible ansible-playbook

我正在一个项目中工作,我们使用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
Run Code Online (Sandbox Code Playgroud)

如果失败,则显示以下消息:ERROR:任务中缺少"action"或"local_action"属性"将本地filetocopy.zip复制到远程(如果存在)"

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

ede*_*ans 29

一个更全面的答案:

如果要在执行某项任务之前检查本地文件是否存在,请参阅以下综合代码段:

- 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
Run Code Online (Sandbox Code Playgroud)

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

- 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
Run Code Online (Sandbox Code Playgroud)


San*_*ick 21

将您的第一步更改为以下内容

- name: copy local filetocopy.zip to remote if exists
  local_action: stat path="../filetocopy.zip"
  register: result    
Run Code Online (Sandbox Code Playgroud)

  • 在当前版本的Ansible中,我不得不添加::false来使其工作.否则,它会给出一个关于无法sudo和失败的错误. (2认同)

小智 11

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

tasks:
- copy: src=/a/b/filetocopy.zip dest=/tmp/filetocopy.zip
  when: '/a/b/filetocopy.zip' | is_file
Run Code Online (Sandbox Code Playgroud)

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

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

  • 显然,这是声明性最强的版本,可以在任何任务中使用,而无需其他任务。在最新版本的Ansible(2.6+)中,当从文件中提供的URL可以看到“ /a/b/filetocopy.zip”是文件时,它可以写为“。 (4认同)