Fetching Multiple Files with Ansible
Using a Loop to Fetch Multiple Files
To fetch multiple files from remote hosts, you can use a loop in your Ansible playbook. Here's an example:
- hosts: all
tasks:
- name: Fetch multiple files from remote host
ansible.builtin.fetch:
src: "{{ item }}"
dest: /local/path/{{ inventory_hostname }}/{{ item | basename }}
flat: yes
loop:
- /path/to/file1.txt
- /path/to/file2.txt
- /path/to/file3.txt
In this example, the ansible.builtin.fetch
module is used within a loop to fetch three different files from the remote host. The src
parameter uses the {{ item }}
variable to specify the file path for each iteration of the loop. The dest
parameter constructs the local file path using the {{ inventory_hostname }}
and {{ item | basename }}
variables, which ensure that the files are saved with the correct names.
Fetching Files Using a List Variable
Alternatively, you can store the list of files to be fetched in a variable and use that variable in the src
parameter. This can be useful if the list of files is dynamic or stored in a separate file. Here's an example:
- hosts: all
vars:
files_to_fetch:
- /path/to/file1.txt
- /path/to/file2.txt
- /path/to/file3.txt
tasks:
- name: Fetch multiple files from remote host
ansible.builtin.fetch:
src: "{{ item }}"
dest: /local/path/{{ inventory_hostname }}/{{ item | basename }}
flat: yes
loop: "{{ files_to_fetch }}"
In this example, the list of files to be fetched is stored in the files_to_fetch
variable, which is then used in the loop
parameter of the ansible.builtin.fetch
module.
Fetching Files Using Wildcards
The Ansible Fetch module also supports the use of wildcards in the src
parameter. This can be useful when you need to fetch multiple files that match a certain pattern. Here's an example:
- hosts: all
tasks:
- name: Fetch log files from remote host
ansible.builtin.fetch:
src: /var/log/*.log
dest: /local/path/{{ inventory_hostname }}/logs/
flat: no
In this example, the src
parameter uses the wildcard *.log
to fetch all log files located in the /var/log
directory on the remote host. The flat: no
option ensures that the directory structure is preserved in the local destination path.
By using these techniques, you can effectively fetch multiple files from remote hosts using the Ansible Fetch module, making it easier to manage and analyze data across your infrastructure.