如何使用Ansible从远程机器获取多个文件到本地

我想用Ansible将文件从远程目录复制到本地目录,但是获取模块允许我只复制一个文件。 我有许多服务器,我需要文件(每个服务器相同的目录),我现在不用Ansible如何做到这一点。

有任何想法吗?

你可能需要注册远程内容,而不是循环,这样的事情应该工作:

- shell: (cd /remote; find . -maxdepth 1 -type f) | cut -d'/' -f2 register: files_to_copy - fetch: src=/remote/{{ item }} dest=/local/ with_items: files_to_copy.stdout_lines 

/remote应该在远程服务器上的目录path中进行更改, /local/目录在主服务器上

你应该使用同步模块来做到这一点。 这使用了rsync的强大function。 它将复制任何深度的文件和目录结构,是防弹和高效的 – 只复制已经改变的实际字节:

 - name: Fetch stuff from the remote and save to local synchronize: src={{ item }} dest=/tmp/ mode=pull with_items: - "folder/one" - "folder/two" 

关键是mode参数:

指定同步的方向。 在推模式下,本地主机或代理是源代码; 在拉模式中,上下文中的远程主机是源。

 - hosts: srv-test tasks: - find: paths="/var/tmp/collect" recurse=no patterns="*.tar" register: file_to_copy - fetch: src={{ item }} dest=/tmp with_items: files_to_copy.stdout_lines 

我没有足够的代表评论,否则我会添加它。

我使用了Kęstutis发布的内容。 我不得不稍作修改

 - shell: (cd /remote; find . -maxdepth 1 -type f) | cut -d'/' -f2 register: files_to_copy - fetch: src=/remote/{{ item }} dest=/local/ with_items: "{{ files_to_copy.stdout_lines }}" 

with_items是我不得不改变的地方。 否则无法find文件。

修正上面的例子

 - hosts: srv-test tasks: - find: paths="/var/tmp/collect" recurse=no patterns="*.tar" register: files_to_copy - fetch: src={{ item.path }} dest=/tmp with_items: "{{ files_to_copy.files }}" 

好吧,如果你使用的是最新版本,比如2.2.1.0,我想我们需要引用这个条目

 - name: use find to get the files list which you want to copy/fetch find: paths: /etc/ patterns: ".*passwd$" use_regex: True register: file_2_fetch - name: use fetch to get the files fetch: src: "{{ item.path }}" dest: /tmp/ flat: yes with_items: "{{ file_2_fetch.files }}"