Tanay Suthar
Tanay Suthar

Reputation: 453

Copy Files from one server to another using Ansible

I want to copy files from one server to another using Ansible. Below is the example

Server A ------> Server B
Server C ------> Server D

I have my one file on Server A and specifically want to copy that file on to the server B, and same for server C to D. Folder to save files to the destination is the same. I can do it for 2 or 3 hosts. But how can I create dynamically for let us say 100 nodes to copy particular single file assign to desired server only.

Upvotes: 3

Views: 12141

Answers (1)

ydaetskcoR
ydaetskcoR

Reputation: 56849

You could use a combination of fetch and copy to do this.

Assuming an inventory that was structured something like this:

[source-servers]
ServerA
ServerC

[dest-servers]
ServerB source-server=ServerA
ServerD source-server=ServerB

And then ran the following fetch task:

- name: fetch file from source servers
  hosts: source-servers
  fetch:
    src: /path/to/file
    dest: /tmp

Would copy the file /path/to/file on ServerA to the Ansible control host under /tmp/ServerA/path/to/file and /path/to/file on ServerB to the Ansible control host under /tmp/ServerB/path/to/file

From here we just then need to make sure that each of the dest-servers has a variable defined that says what server(s) it is paired with under a host var either in a separate host vars file or in line in the inventory as above.

And then we can put the right file on the right dest-server with this copy task:

- name: copy the paired files to the right servers
  hosts: dest-servers
  copy:
    src: "/tmp/{{ source-server }}/path/to/file"
    dest: /path/to/dest

Upvotes: 9

Related Questions