Ansible Pilot

Copy files from remote hosts - Remote to Local - Ansible module fetch

Access the Complete Video Course and Learn Quick Ansible by 200+ Practical Lessons

How to Copy files from remote hosts with Ansible? Simple code how to copy /var/log/messages from managed host to controller.

How to copy files from remote hosts with Ansible?

I’m going to show you a live demo with some simple Ansible code. I’m Luca Berton and welcome to today’s episode of Ansible Pilot

Ansible copy files from remote hosts

Today we’re talking about Ansible module fetch. The full name is ansible.builtin.fetch which means is part of the collection of modules “builtin” with ansible and shipped with it. This module is pretty stable and out for years. The purpose is to copy files from remote locations. Please note that the opposite is done by Ansible copy module.

Parameters

The parameter list is pretty wide but I’ll summarize the most useful.

The only required parameter is “dest” which specifies a directory to save the file into and the “src” specifies the source files in the remote hosts. It must be a file, not a directory.

The “fail_on_missing” boolean is set to true so the task is going to fail if the file doesn’t exist.

The file is going to be transferred and validate in the source and the destination with a checksum. If we don’t want this behavior we could override with the “validate_checksum” option.

The “flat” option allows you to override the default behavior of appending hostname/path/to/file to the destination.

Demo

Let’s jump in a real-life playbook to copy files from remote hosts with Ansible

---
- name: fetch module demo
  hosts: all
  become: true
  vars:
    log_file: "/var/log/messages"
    dump_dir: "logs"
  tasks:
    - name: fetch log
      ansible.builtin.fetch:
        src: "{{ log_file }}"
        dest: "{{ dump_dir }}"

code with ❤️ in GitHub

Recap

Now you know how to Copy files to remote hosts with Ansible. Subscribe to the YouTube channel, Medium, Website and Twitter to not miss the next episode of the Ansible Pilot.

Academy

Learn the Ansible automation technology with some real-life examples in my

My book Ansible By Examples: 100+ Automation Examples For Linux and Windows System Administrator and DevOps

Access the Complete Book and Learn Quick Ansible by 200+ Examples

Want to keep this project going? Please donate

Access the Complete Video Course and Learn Quick Ansible by 200+ Practical Lessons
Trustpilot
Follow me

Subscribe not to miss any new releases

August 12, 2021

FREE Top 10 Best Practices

Top 10 Best Practices of Ansible Automation: save time, reduce errors and stress