Exploring Ansible Modules

Athira KK
8 min readDec 28, 2023

--

Hey Techies…👋

In this blog, we’re going to explore Ansible Modules : your toolkit for seamless configuration and management. From package installation to file manipulation, user administration, and service control.

Ansible modules are fundamental components of Ansible automation, serving as standalone scripts designed to perform specific tasks on managed nodes.

The purpose of building Ansible modules is to abstract complexity, offering end-users a streamlined way to execute automation tasks without exploring small details. By leveraging modules, Ansible users can perform tasks efficiently, and the cognitive load associated with more complex operations is abstracted away.

Key characteristics of Ansible modules include:

Task Execution:

Modules are the building blocks for executing tasks in Ansible playbooks. They provide the actual implementation of the tasks specified in the playbook.

Abstraction of Complexity:

Modules abstract the complexity of underlying operations, allowing users to focus on the desired outcome rather than intricate details. This simplification enhances the usability of Ansible for automation tasks.

Diversity of Functions:

Ansible modules cover a wide range of functions, from basic tasks like file manipulation and package installation to complex operations involving cloud resources, databases, and more.

Standardization:

Ansible modules follow a standardized structure and interface, facilitating consistency and predictability across different modules. This uniformity simplifies the learning curve for users.

Idempotency:

Modules are designed to be idempotent, meaning that applying the same module multiple times has the same result as applying it once. This ensures predictability and reliability in the execution of playbooks.

Dynamic Input Handling:

Modules accept dynamic input parameters, allowing users to customize the behavior of tasks based on specific requirements. This flexibility enhances the adaptability of Ansible to different use cases.

Community and Custom Modules:

Ansible has a vast collection of community-contributed modules, covering a wide array of technologies and services. Users can also create custom modules to extend Ansible’s functionality for specialized tasks.

Remote Execution:

Modules are executed on remote hosts, allowing Ansible to manage and configure systems without requiring agents on the managed nodes.

Output Handling:

Modules provide structured output, making it easy for subsequent tasks or scripts to parse and interpret the results. This structured output is often in JSON format.

Declarative Nature:

Ansible playbooks, which utilize modules, follow a declarative syntax, specifying the desired state of the system rather than prescribing the steps to reach that state. This contributes to the simplicity and readability of Ansible automation.

Here’s an example of an Ansible task using the yum module to install a specific version of the Apache HTTP Server (httpd package) on a CentOS machine:

---
- name: Install Apache HTTP Server with a Specific Version on CentOS
hosts: all
become: yes # This allows the task to run with elevated privileges (sudo)

tasks:
- name: Install Apache HTTP Server
yum:
name: httpd # Package name for Apache HTTP Server
state: present # Ensure the package is installed

- name: Ensure a Specific Version of Apache is Installed
yum:
name: httpd-2.4.6-90.el7.centos # Specify the desired version
state: present

The first task installs the Apache HTTP Server (httpd package) using the yum module. The state: present ensures that the package is installed.

The second task uses the yum module again to ensure a specific version of Apache is installed. In this example, it’s installing version 2.4.6–90.el7.centos of the httpd package.

Most Useful & Common Ansible Modules in Centos

💡yum:

Description: The yum module allows you to perform tasks such as installing, updating, or removing packages.
Use Case: Installing, updating, or removing packages.

Here’s a basic example of using the yum module to install a package:

---
- name: Install Apache HTTP Server
hosts: all
become: yes # This allows the task to run with elevated privileges (sudo)

tasks:
- name: Install Apache HTTP Server
yum:
name: httpd
state: present # Ensure the package is installed

💡service:

Description: The service module in Ansible is used to manage services on remote hosts. It allows you to start, stop, restart, enable, or disable services.
Use Case: Starting, stopping, or restarting services.

Here’s a basic example of using the service module to ensure that the Apache HTTP Server is running:

---
- name: Manage Apache Service
hosts: all
become: yes # This allows the task to run with elevated privileges (sudo)

tasks:
- name: Ensure Apache service is running
service:
name: httpd
state: started
enabled: yes

💡file:

Description: The file module in Ansible is used to manage files and directories on remote hosts. It allows you to create, delete, modify, or set permissions for files and directories.
Use Case: Creating, deleting, or modifying files and directories.
Here’s an overview of the file module:

---
- name: Manage Files and Directories
hosts: all
become: yes # This allows the task to run with elevated privileges (sudo)

tasks:
- name: Create a directory
file:
path: /path/to/directory
state: directory

- name: Create a file with content
file:
path: /path/to/directory/myfile.txt
state: touch
content: "Hello, Ansible!"

💡template:

Description: The template module in Ansible is used to dynamically generate files on remote hosts using Jinja2 templating. It allows you to create configuration files with dynamic content.
Use Case: Creating configuration files with dynamic content.

Here’s a basic example of using the template module to generate a configuration file:

---
- name: Manage Configuration File with Template
hosts: all
become: yes # This allows the task to run with elevated privileges (sudo)

tasks:
- name: Create a configuration file from template
template:
src: /path/to/template.conf.j2
dest: /etc/myapp/myapp.conf

🌐Jinja2 Templating:

Inside the Jinja2 template file (e.g., template.conf.j2), you can use Jinja2 syntax to include variables, conditionals, and loops. Here's a simple example:

# template.conf.j2

# Configuration file for MyApp
database_url = {{ database_url }}
debug_mode = {{ debug_mode | default(false) }}

💡user:

Description: The user module in Ansible is used to manage user accounts on remote hosts. It allows you to create, modify, or remove user accounts and associated attributes.
Use Case: Creating, modifying, or removing user accounts.

Here’s a basic example of using the user module to create a new user:

---
- name: Manage User Account
hosts: all
become: yes # This allows the task to run with elevated privileges (sudo)

tasks:
- name: Create a new user
user:
name: john_doe
password: "$6$random_salt$hashed_password"
groups: users

💡copy:

Description: The copy module in Ansible is used to copy files from the local machine to remote hosts. It allows you to transfer files and set their ownership and permissions.
Use Case: Transferring configuration files or scripts to target systems.

Here’s a basic example of using the copy module to transfer a file to remote hosts:

---
- name: Copy Files to Remote Hosts
hosts: all
become: yes # This allows the task to run with elevated privileges (sudo)

tasks:
- name: Copy a file
copy:
src: /path/to/local/file.txt
dest: /path/on/remote/host/file.txt

💡command:

Description: The command module in Ansible is used to execute commands on remote hosts. It runs the command in the default shell (/bin/sh) on the remote host, allowing you to perform various tasks.
Use Case: Running basic command-line operations.

Here’s a basic example of using the command module to run a simple command on remote hosts:

---
- name: Execute Command on Remote Hosts
hosts: all
become: yes # This allows the task to run with elevated privileges (sudo)

tasks:
- name: Run a command
command: ls /path/to/directory

💡shell:

Description: The shell module in Ansible is used to execute commands in a shell on remote hosts. It allows you to run more complex command sequences or scripts compared to the command module.
Use Case: Running complex command sequences or scripts.

Here’s a basic example of using the shell module to run a command in a shell on remote hosts:

---
- name: Execute Shell Command on Remote Hosts
hosts: all
become: yes # This allows the task to run with elevated privileges (sudo)

tasks:
- name: Run a shell command
shell: ls /path/to/directory

💡cron:

Description: The cron module allows you to create, modify, or remove cron jobs.
Use Case: Scheduling periodic tasks.

Here’s a basic example of using the cron module to create a cron job:

---
- name: Manage Cron Jobs
hosts: all
become: yes # This allows the task to run with elevated privileges (sudo)

tasks:
- name: Create a cron job
cron:
name: "My Daily Task"
minute: "0"
hour: "2"
job: "/path/to/script.sh"

💡lineinfile:

Description: The lineinfile module in Ansible is used to ensure that a particular line is present or absent in a file. It’s commonly used to manage configuration files by adding, modifying, or removing specific lines.
Use Case: Modifying configuration files by adding, modifying, or removing specific lines.

Here’s a basic example of using the lineinfile module to add a line to a configuration file:

---
- name: Manage Configuration File
hosts: all
become: yes # This allows the task to run with elevated privileges (sudo)

tasks:
- name: Add a line to a file
lineinfile:
path: /path/to/configfile
line: 'new_line_to_add'

💡git:
Description: The git module in Ansible is used to manage Git repositories on remote hosts. It allows you to clone repositories, update them, and perform various Git-related tasks.
Use Case: Manage Git repositories by clone,add,update and perform various Git tasks

Here’s a basic example of using the git module to clone a Git repository:

---
- name: Manage Git Repository
hosts: all
become: yes # This allows the task to run with elevated privileges (sudo)

tasks:
- name: Clone a Git repository
git:
repo: https://github.com/example/repo.git
dest: /path/to/local/clone

Take a look at the following example, covering tasks such as package installation, file management, user administration, and service management.

---
- name: System Configuration
hosts: all
become: yes # This allows the tasks to run with elevated privileges (sudo)

tasks:
- name: Update system packages
yum:
name: '*'
state: latest
when: ansible_os_family == 'RedHat'

- name: Ensure the NTP service is installed and running
service:
name: ntpd
state: started
enabled: yes

- name: Create a system user
user:
name: sysadmin
group: wheel
password: "$6$random_salt$hashed_password"
shell: /bin/bash

- name: Ensure SSH key for sysadmin user
authorized_key:
user: sysadmin
key: "{{ lookup('file', '/path/to/local/public_key.pub') }}"
state: present

- name: Configure the firewall to allow SSH
firewalld:
service: ssh
permanent: yes
state: enabled
notify: Reload Firewalld

handlers:
- name: Reload Firewalld
command: firewall-cmd --reload

Explanation:

✅Update system packages: The yum module ensures that all system packages on CentOS are updated to the latest version.

✅Ensure the NTP service is installed and running: The service module ensures that the NTP (Network Time Protocol) service is installed, started, and set to start on boot.

✅Create a system user: The user module creates a user named ‘sysadmin’ belonging to the ‘wheel’ group with a specified password and shell.

✅Ensure SSH key for sysadmin user: The authorized_key module adds an SSH public key to the authorized_keys file for the ‘sysadmin’ user, allowing secure access.

✅Configure the firewall to allow SSH: The firewalld module ensures that the firewall allows incoming SSH connections. The handler triggers a firewall reload to apply changes.

In summary, Ansible modules are the backbone of automation, offering powerful tools for managing diverse tasks. The modules highlighted here provide a solid foundation, and as your needs evolve, exploring additional modules using the ‘ansible-doc <module-name>’ command opens the door to endless possibilities. Ansible’s modular architecture empowers you to streamline and customize automation workflows, making it a versatile and indispensable tool for IT orchestration and configuration management.

I hope that this blog has provided you with valuable insights into the practical and beneficial aspects of Ansible Modules.

💹Next day — Understanding Ansible Facts: A Handbook of Dynamic Variables.

⭐⭐⭐ Enjoy your learning….!!! ⭐⭐⭐

--

--

Athira KK

AWS DevOps Engineer | Calico Big Cats Ambassador | WomenTech Global Ambassador | LinkedIn Top Cloud Computing Voice