Fetch - not working correctly

I’ve written a playbook with some roles and I can’t seem to get fetch working correctly. Below is the part of the play in question:

  • hosts: Server1 (which I consider the controller and where I’m running this play)
    gather_facts: false
    become: true
    roles:
    • 03-Fetch_files

In roles: 03-Fetch_files

  • name: Fetch key file
    ansible.builtin.fetch:
    src: /etc/certificate-authority/host1.fqdn.key
    dest: /tmp
    flat: no

Here’s what’s happening. Host 1 is just a host I’m using to test. Ultimately there will be over 500 hosts I need to fetch key (and csr) files from.
If I run this play with an entry for Server1 in hosts file, and run the play on Server 1, it’s pulling the key file from host1, but it’s creating a directory, called Server1/etc/certificate-authority/host1.fqdn.key in /tmp (which is just for testing right now). That’s no good. Again, since ultimately I’m going to need to fetch over 1000 files (key and csr) and need them in directories named for the host.

If I run this play from host1, with the entry in “hosts” changed to host1, then it creates a directory called “Server1/etc/certificate-authority/host1.fqdn.key”.

I’m trying to fetch keys to the controller, Server1, from host1, and want the dir structure to look like: host1/host1.fqdn.key.

I also can’t figure out why it’s picking up the “/etc/certificate-authority” and placing that name as part of the dir structure.

Can anyone help untangle my brain?

I’ve also tried changing src in the role to:

src: /etc/certificate-authority/“{{ ws_hostname }}.fqdn.key” but then I get "file doesn’t exist errors, although the key is there.

ws_hostname is defined in vars as inventory_hostname_short

I don’t think it is. As written above, no host1 is involved. It’s running with Server1 as both the Ansible controller and the target host. It’s fetching from the controller to the controller.

That’s correct, because it’s fetching the file from Server1.

That’s because you have flat: no. Change that to flat: true to eliminate the intermediate directory levels in the fetch destination.

Then you want something like this:

- name: Fun with ansible.builtin.fetch
  hosts: host1,host2,host3  # Hosts and/or host groups to fetch _from_, NOT your controller (necessarily)
  gather_facts: false
  become: true
  tasks:  # This task could be in a role. Trying to keep it simple.
    - name: Fetch key files from target hosts
      ansible.builtin.fetch:
        src: /etc/certificate-authority/{{ inventory_hostname }}.fqdn.key
        dest: /tmp/{{ inventory_hostname }}/  # This will create host directories
        flat: true  # This avoids creating the intermediate directories

(BTW, see this post in its raw format to see how to get your yaml to look good in your posts.)

2 Likes

Thank you. This works just the way I need it to, and even better, I understand Fetch now.