Introduction
Automation is key in modern IT infrastructure management. Ansible, a powerful automation tool, makes it easy to manage complex environments. One of the many tasks you can automate with Ansible is reading content from multiple files. This article will guide you through a simple playbook that reads content from text files within a specified directory and displays the content.
Understanding the Playbook
The provided playbook is designed to run on the local host and performs the following tasks:
1. List all text files in the specified directory and its subdirectories.
2. Read the content from each text file.
3. Display the content of the files.
Let's break down each section of the playbook to understand how it works.
Listing Files in a Directory
First, we use the ansible.builtin.find module to list all text files in the specified directory (/path/to/your/directory). The recurse: yes option ensures that the search includes subdirectories.
``yaml
- name: List files in directory
ansible.builtin.find:
paths: "/path/to/your/directory"
recurse: yes
patterns: "*.txt"
register: files_list
`
The results are stored in a variable called files_list.
Reading Content from Each File
Next, we initialize an empty list to store the file contents using ansible.builtin.set_fact.
`yaml
- name: Read content from each file
ansible.builtin.set_fact:
file_contents: []
`
We then use a loop to iterate over each file in files_list.files. The ansible.builtin.slurp module reads the content of each file and stores it in the slurped_files variable. The loop_control ensures we use a custom loop variable item_info.
`yaml
- name: Read content from each file
ansible.builtin.slurp:
src: "{{ item.path }}"
loop: "{{ files_list.files }}"
register: slurped_files
loop_control:
loop_var: item
- name: Set fact for file contents
ansible.builtin.set_fact:
file_contents: "{{ slurped_files.results | map(attribute='content') | map('b64decode') | list }}"
`
Displaying File Contents
Finally, we display the content of the files using the ansible.builtin.debug module.
`yaml
- name: Display file contents
ansible.builtin.debug:
var: file_contents
`
Complete Playbook
Here's the complete playbook for reference:
``yaml
---
- name: Read content from multiple files
hosts: localhost
gather_facts: no
tasks:
- name: List files in directory
ansible.builtin.find:
paths: "/path/to/your/directory"
recurse: yes
patterns: "*.txt"
register: files_list
- name: Read content from each file
ansible.builtin.slurp:
src: "{{ item.path }}"
loop: "{{ files_list.files }}"
register: slurped_files
loop_control:
loop_var: item
- name: Set fact for file contents
ansible.builtin.set_fact:
file_contents: "{{ slurped_files.results | m