首页 > 解决方案 > 带有通配符的Ansible复制文件?

问题描述

在我的文件目录中,我有各种文件,具有相似的名称结构:

data-example.zip
data-precise.zip
data-arbitrary.zip
data-collected.zip

我想使用 Ansible 传输远程机器的 /tmp 目录中的所有这些文件,而无需明确指定每个文件名。换句话说,我想传输每个带有“data-”星号的文件。

这样做的正确方法是什么?在一个类似的帖子中,有人建议使用该with_fileglob关键字,但我无法让它发挥作用。有人可以为我提供一个如何完成上述任务的例子吗?

标签: ansiblecopywildcardprovisioning

解决方案


方法1:查找所有文件,将它们存储在一个变量中并将它们复制到目标。

- hosts: lnx
  tasks:
    - find: paths="/source/path" recurse=yes patterns="data*"
      register: file_to_copy
    - copy: src={{ item.path }} dest=/dear/dir
      owner: root
      mode: 0775
      with_items: "{{ files_to_copy.files }}"

使用remote_src: yes将远程机器中的文件从一个路径复制到另一个路径。

Ansible 文档

方法 2:Fileglob

- name: Copy each file over that matches the given pattern
  copy:
    src: "{{ item }}"
    dest: "/etc/fooapp/"
    owner: "root"
    mode: 0600
  with_fileglob:
    - "/playbooks/files/fooapp/*"

Ansible 文档


推荐阅读