Ansible copy and extract archived file from remote server to another

ansibletar

I'm generating an archived file on remote server A. e.g.
/tmp/website.tar.gz
and want to transfer/copy and extract the file to the remote server B (/var/www).
How do I do that in Ansible?

My Ansible script to create archived file:

- name: archive files
  shell: tar -zczf /tmp/website.tar.gz .
  args:
    chdir: "{{ source_dir }}"
  tags: release

- name: copy archived file to another remote server and unpack to directory /var/www. unresolved..

Update:
Can I use the rsync module? . I'm trying to use the synchronize module to copy the archived file to the remote server B:

- name: copy archived file to another remote server and unpack to directory /var/www
  synchronize:
    src: /tmp/website.tar.gz
    dest: /var/www
    rsync_opts:
      - "--rsh=ssh -i /home/agan/key/privatekey"
  delegate_to: remote_server_b
  tags: test

it produces an error:

fatal: [remote_server_b] => SSH Error: Permission denied (publickey).
    while connecting to xxx.xxx.xxx.129:22
It is sometimes useful to re-run the command using -vvvv, which prints SSH debug output to help diagnose the issue.

FATAL: all hosts have already failed -- aborting

I have a private key for server B, how to remotely access the server B using private key?

Best Answer

Your current playbook is attempting to rsync from server A to server B but it doesn't have permission to do so (lack of public key as your error shows).

You can either put server A's public key on server B (if these boxes should be regularly communicating with each other) or you can bring the file back to the Ansible host (which should have access to both servers) and then push it back to server B.

You can use the fetch module for things like this. It's basically like the copy module but in reverse.

An example playbook might look something like this:

- hosts: serverA
  tasks:
    - name: archive files on serverA
      shell: tar -czf /tmp/website.tar.gz .
      args:
        chdir: "{{ source_dir }}"
      tags: release
    - name: fetch the archive from serverA
      fetch:
        src: /tmp/website.tar.gz
        dest: /tmp/website.tar.gz

- hosts: serverB
  tasks:
    - name: copy the archive to serverB
      copy:
        src: /tmp/website.tar.gz
        dest: /tmp/website.tar.gz
Related Topic