Ansible Copy File to Another Server
Create some files (via templating) on the source server as usual:
- name: Create backup configuration files
template:
src: "backup.yml.j2"
dest: "/tmp/backup.yml"
We then want to copy this file to another server, e.g. other.example.com. To do this we need to use delegate_to which will run a task on another server.
You can delegate either scp
or synchronize
(which uses rsync under the hood) to get the desired result.
with scp
- name: Copy configuration to Backup server
become: true
shell: "scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null admin@{{ inventory_hostname }}:/tmp/backup.yml /etc/backups/backup.yml"
delegate_to: other.example.com
with synchronize
- name: Copy configuration to Backup server
synchronize:
src: "/tmp/something.yml"
dest: "/etc/backup/config/backup.yml"
mode: pull
delegate_to: other.example.com
Note that mode: pull
is important since the command (rsync) is run on the other server and it wants to pull the file.