Ansible read remote file

In this tutorial, How to use Ansible to read a remote file? Ansible the essential for DevOps Roles.

Ansible read remote file using slurp module

I use the slurp module to read a remote file.

- hosts: server1
  tasks:
  - name: slurp file
    slurp:
     src: /home/vagrant/devopsroles
    register: slurp_remote_file

  - name: Read file
    debug:
     msg: "{{ slurp_remote_file['content'] | b64decode }}"
Ansible read remote file

The terminal output as below

Ansible shell module

Using the shell module cat command to read a remote file

- hosts: server1
  tasks:
    - name: cat file
      shell: cat /home/vagrant/devopsroles
      register: cat_content_file

    - name: echo file
      debug:
        msg: "{{ cat_content_file.stdout }}"

The terminal output as below

Ansible read remote file shell module

Ansible fetch module

To read a remote file using Ansible, you can use the fetch module. The fetch module allows you to retrieve files from remote hosts and store them locally on the Ansible control machine.

Here’s an example task to read a remote file:

- name: Read remote file
  hosts: your_host
  gather_facts: false
  tasks:
    - name: Fetch remote file
      fetch:
        src: /path/to/remote/file.txt
        dest: /path/to/local/directory/

In this example, replace your_host with the target host or group of hosts where the remote file is located. Set the src parameter to the path of the remote file you want to read. Set the dest parameter to the local directory path where you want to store the fetched file.

Conclusion

Make sure you have proper SSH access and permissions to read the remote file on the target host(s) before running this playbook.

Through the article, you can use Ansible read remote file. I hope will this your helpful. For more details refer to Ansible tutorial.

About HuuPV

My name is Huu. I love technology and especially Devops Skill such as Docker, vagrant, git so forth. I likes open-sources. so I created DevopsRoles.com site to share the knowledge that I have learned. My Job: IT system administrator. Hobbies: summoners war game, gossip.
View all posts by HuuPV →

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.