Intro

When it comes to infrastructure automation, Ansible stands out as one of the most popular and powerful tools today. At the heart of Ansible’s automation capabilities are its modules, which serve as the primary building blocks for defining tasks and actions in your Ansible playbooks and roles. In this post, we’re going to dive into the opportunity-rich world of Ansible modules, focusing here on the foundational ansible.builtin collection, which is where every Ansible user should likely start when they’re looking for ways to bring new automation features and functionality to your infrastructure.

This post expands on Level Up’s previous coverage of “Your First 10 Ansible Modules“.

What Are Ansible Modules, Anyway?

In Ansible, modules are ultimately just small, self-contained scripts or programs that carry out specific tasks for you, usually (but certainly not always!) on remote hosts. These tasks can range from simple operations like creating directories or managing files… to more complex actions like configuring provisioning hosts or orchestrating application deployments. Modules abstract the underlying system-specific details and provide a consistent and reliable way to manage different aspects of your infrastructure. If we think of hosts as being the “nouns” of Ansible, then modules are basically the “verbs”, and we can mix and match modules to achieve just about any imaginable automation workflow in modern computing environments.

RELATED CONTENT: Level Up’s YouTube playlist on using Red Hat® Ansible Automation Platform (AAP) for Linux Configuration Management

Understanding Ansible Builtin Modules

Ansible helpfully comes with a deep collection of builtin modules that cover a pretty wide range of use cases. As you’ll see below, these modules are quite capable of doing a lot of the heavy-lifting in your Day 1 and Everyday Linux configuration management automations (and yes, there are equivalents for many/most of these in the ansible.windows collection). We’ve grouped them into 10 fairly logical categories (there’s admittedly some overlap in categories in practice), picked some worth calling out in each category, and put a spotlight 5 modules in particular in the more intermediate/advanced end of the spectrum– all to give you some fast ideas on how you can start getting the most out of what’s already included in Ansible, right now, today!

Inventory Management:

  1. ping module – Try to connect to host, verify a usable python and return pong on success
  2. group_by module – Create Ansible groups based on facts
  3. add_host module – Add a host (and alternatively a group) to the ansible-playbook in-memory inventory. Super helpful for provisioning situations. Here’s a playbook sketch:

---
- name: Provision and Configure RHEL EC2 Instance
  hosts: localhost
  gather_facts: false
  collections:
    - amazon.aws
  tasks:
    - name: Create RHEL EC2 instance
      amazon.aws.ec2_instance:
        instance_type: t2.micro
        image_id: ami-XXXXXXXXXXXXXXXXX  
        region: us-east-1  
        key_name: your-key-pair  
        count: 1
        state: present
        wait: yes
      register: ec2_instance

    - name: Add the new instance to the inventory
      ansible.builtin.add_host:
        name: "{{ ec2_instance.instances[0].private_ip }}"
        ansible_ssh_user: ec2-user 
        ansible_ssh_private_key_file: /path/to/your/key.pem  
        ansible_python_interpreter: /usr/bin/python3
      when: ec2_instance.changed

- name: Configure /etc/motd on the new instance
  hosts: ec2_instances
  tasks:
    - name: Set custom message in /etc/motd
      ansible.builtin.template:
        src: motd.j2  
        dest: /etc/motd
      become: true

Package Management:

  1. apt module – Manages apt-packages
  2. dnf module – Manages packages with the dnf package manager
  3. package module – Generic OS package manager
  4. yum module – Manages packages with the yum package manager
  5. yum_repository module – Add or remove YUM repositories. Fairly common in orgs which may use non-Red Hat mirrors, etc. Here’s a playbook sketch:

---
- name: Manage YUM Repositories
  hosts: all
  become: true 
  tasks:
    - name: Add a new YUM repository
      ansible.builtin.yum_repository:
        name: example_repo
        description: Example Repository
        baseurl: http://example.com/repo
        gpgcheck: yes
        gpgkey: http://example.com/repo/RPM-GPG-KEY
        enabled: yes
      notify:
        - Refresh YUM cache

    - name: Remove an existing YUM repository
      ansible.builtin.yum_repository:
        name: old_repo
        state: absent
      notify:
        - Refresh YUM cache

  handlers:
    - name: Refresh YUM cache
      ansible.builtin.command: yum clean all

File and Configuration Management:

  1. blockinfile module – Insert/update/remove a text block surrounded by marker lines
  2. copy module – Copy files to remote locations
  3. file module – Manage files and file properties
  4. template module – Template a file out to a target host
  5. fetch module – Fetch files from remote nodes. Because sometimes you need to pull files back for further processing, historical reporting, etc. Here’s a playbook sketch:

---
- name: Fetch httpd.conf from Apache Hosts
  hosts: web
  tasks:
    - name: Fetch httpd.conf from remote host
      ansible.builtin.fetch:
        src: /etc/httpd/conf/httpd.conf 
        dest: /tmp/  # Will be saved to /tmp/host1//etc/httpd/conf/httpd.conf
        validate_checksum: true 

Task Execution and Control:

  1. command module – Execute simple commands on targets. Cannot handle pipelines or redirects.
  2. raw module – Bypasses SSH to run commands
  3. script module – Runs a local script on a remote node after transferring it
  4. shell module – Execute shell commands on targets. CAN handle pipelines and redirects.
  5. fail module – Fail with custom message. Makes an Ansible playbook fail when a condition is met. Here’s a playbook sketch:

---
- name: Check Website Response Code
  hosts: localhost  
  tasks:
    - name: Curl the website
      ansible.builtin.command: "curl -I -s https://example.com"
      register: curl_output
      ignore_errors: yes  # Ignore non-zero exit codes

    - name: Print curl output
      ansible.builtin.debug:
        var: curl_output.stdout

    - name: Check response code
      ansible.builtin.fail:
        msg: "The website returned a 500 Internal Server Error."
      when: "'HTTP/2 500' in curl_output.stdout"

User and Group Management:

  1. group module – Add or remove groups
  2. user module – Manage user accounts

System and Configuration Management:

  1. gather_facts module – Gathers facts about remote hosts
  2. hostname module – Manage hostname
  3. known_hosts module – Add or remove a host from the known_hosts file
  4. setup module – Gathers facts about remote hosts
  5. systemd_service module – Manage systemd units

Role and Playbook Execution:

  1. import_playbook module – Import a playbook
  2. import_tasks module – Import a task list
  3. include_role module – Load and execute a role
  4. include_tasks module – Dynamically include a task list
  5. include_vars module – Load variables from files, dynamically within a task

Web and Network Services:

  1. get_url module – Downloads files from HTTP, HTTPS, or FTP to node
  2. uri module – Interacts with webservices

Service and Process Management:

  1. service module – Manage services
  2. service_facts module – Return service state information as fact data
  3. reboot module – Reboot a machine. Here’s a playbook sketch:

---
- name: Patch and Reboot RHEL Hosts
  hosts: all
  become: true  
  tasks:
    - name: Update packages via dnf
      ansible.builtin.dnf:
        name: '*'
        state: latest
      when: ansible_os_family == 'RedHat'  

    - name: Reboot the system
      ansible.builtin.reboot:
        reboot_timeout: 300
      when: ansible_os_family == 'RedHat'

Version Control and Repository Management:

  1. git module – Deploy software (or files) from git checkouts
  2. subversion module – Deploys a subversion repository
  3. rpm_key module – Adds or removes a gpg key from the rpm db

Commonly Used Module Parameters

Pro tip! Every Ansible module comes with specific parameters that allow you to customize its behavior. Here are some parameters you’ll frequently encounter when you’re using Ansible modules:

  • name: A human-readable name for the task.
  • state: Defines the desired state of the resource (e.g., present, absent, started, stopped).
  • src and dest: Paths to source and destination files or directories.
  • vars: Variables to pass to the module.
  • with_items or loop: Iterate over a list of items.
  • register: Store the result of a task for later use.
  • when: Apply a task conditionally based on a specified condition.

Ansible Galaxy and Red Hat Certified Collections

In addition to built-in modules, Ansible has a vast ecosystem of community-contributed modules available on Ansible Galaxy. Red Hat® also hosts Certified Content for Ansible Automation Platform® for AAP customers (both of which will be the subjects of future posts). These content hubs bring you modules which can dramatically extend Ansible’s functionality for you, covering the broadest possible spectrum of applications and systems.

Conclusion

Ansible modules are basically the propellers of the aircraft carrier that is Red Hat’s Ansible Automation Platform, providing a powerful and flexible way to manage and automate various aspects of your IT infrastructure. By understanding the essential built-in modules and their parameters, you’re now well-equipped to begin tackling a wide range of automation tasks in your organization.

As you dig deeper into Ansible, be sure to forget to explore community-contributed modules and keep up with the ever-evolving Ansible ecosystem. Armed with these resources, you’ll be on your way to becoming an Ansible automation expert.

In upcoming blog posts, we’ll be exploring a variety of Ansible topics, including custom modules, more on playbooks and roles, as well as best practices for managing complex infrastructure and applications. Stay tuned for more insights into the world of Ansible automation!

Get the latest from Level Up delivered to your inbox– DevOps Automation and Cloud news, tips & tricks.

Select list(s) to subscribe to


By submitting this form, you are consenting to receive marketing emails from: Level Up, 20929 Ventura Blvd Ste 47 #265, Woodland Hills, CA, 91364. You can revoke your consent to receive emails at any time by using the SafeUnsubscribe® link, found at the bottom of every email. Emails are serviced by Constant Contact

Spread the word. Share this post!