首页 文章

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

提问于
浏览
23

我正在一个项目中工作,我们使用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

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

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

5 回答

  • 21

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

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

    一个更全面的答案:

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

    - 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
    

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

    - 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

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

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

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

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

  • 2

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

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

    这个怎么样?

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

    如果文件存在于本地,则会将文件复制到目标 . 如果它不存在,它就不会执行任何操作,因为忽略了错误 .

相关问题