How to copy a file between two machines using ansible

I need to copy file form machine A to machine B whereas my control machine from where i run all my ansible tasks is machine C(local machine).

I have tried the following

use scp command in shell module of ansible

hosts: machine2

user: user2

tasks:

  • name: Copy file from machine1 to machine2

shell: scp user1@machine1:/path-of-file/file1 /home/user2/file1

This approach just goes on and on never ends.

use fetch & copy modules

hosts: machine1

user: user1

tasks:

  • name: copy file from machine1 to local

fetch: src=/path-of-file/file1 dest=/path-of-file/file1

hosts: machine2

user: user2

tasks:

  • name: copy file from local to machine2

copy: src=/path-of-file/file1 dest=/path-of-file/file1

This approach throws me an error as follows:

error while accessing the file /Users//.ansible/cp/ansible-ssh-machine2-22-, error was: [Errno 102] Operation not supported on socket: u’/Users//.ansible/cp/ansible-ssh-machine2-22-’

Any suggestions would help.

Definitely don’t invoke a scp from a shell module, as ansible is not meant to manually call ssh in a nested call to another ssh activity, and that will cause all forms of confusion.

The copy module is the way to go.

It looks like for some weird reason your username, as configured in the control persist path, isn’t coming out right on your Mac. You can consider
removing ControlPersist out of SSH args, but I’d just fix the control socket path in ansible.cfg instead. It’s a seperate option.

What version of Ansible are you using?