使用Ansible在远程主机之间复制一个文件



我有两个远程服务器(Prod和Demo(,我想将最新的文件从Prod中的一个特定文件夹复制到Demo中的另一个文件夹。只能复制一个文件。

我可以在Prod中找到最新的文件,使用:

- name: Get files in folder
find:
paths: "/path_in_prod/arch/"
register: found_files
become: true
become_user: root
delegate_to: "{{ prod_server }}"
when: copy_content_from_prod is defined
- name: Get latest file
set_fact:
latest_file: "{{ found_files.files | sort(attribute='mtime', reverse=true) | first }}"
become: true
become_user: root
delegate_to: "{{ prod_server }}"
when: copy_content_from_prod is defined

我可以检查我有正确的文件(调试(。

当我尝试用复制文件时

- name: Fetch the file from prod
fetch: src= {{ latest_file.path }} dest=buffer/ flat=yes
delegate_to: "{{ prod_server }}"
- name: Copy the file to demo
copy: src=buffer/{{ latest_file.path | basename }} dest=/path_in_demo/in

我得到了一个";找不到文件";错误但如果我查找文件,它就在那里(Prod上的latest_file.path(。

这是错误信息

fatal: [demoServerHost -> ProdServerHost ]: FAILED! => {"changed": false, "msg": "file not found: "}

我不知道我是否正确解释了错误消息,但它似乎是在Demo中查找以便复制到Prod上?

我也遇到过类似的问题,复制任务无限期挂起。这是我的示例,它不是特定于站点的(将使用选项识别站点和用户(。我找到的最简单的解决方案是直接使用外壳模块scp:

-   name: scp files onto '{{ target_destination }}' looping for each file on '{{ target_source }}'
shell: 'scp {{ hostvars[target_source].ansible_user }}@{{ hostvars[target_source].ansible_host }}:/opt/{{ hostvars[target_source].ansible_user }}/{{ item }} /opt/{{ destuser.stdout }}'
loop: '{{ diffout.stdout_lines }}'
when: diffout.stdout != ""

一些注意事项:

  • "target_source";以及";target_destination";使用额外的vars选项定义
  • diffout是比较"文件夹"上的文件夹的较早任务;Prod";以及";Demo";并显示要复制的任何新文件
  • 该任务在";target_destination";(在我的案例中是Prod(
  • hostvars[target_source]将查看";target_source";库存中的主机
  • 这起到了";"拉";在我的情况下从Demo到Prod;Demo";没有权限,则可以将任务委派给";Prod";并重新排列scp以查找";Demo";vars从";Prod">

最新更新