Exploring Ansible's set_fact Module with Example
Ansible is an open-source automation tool widely used for configuration management, application deployment, and orchestration. It simplifies the process of managing IT infrastructure by allowing you to define desired state configurations in a declarative manner. One powerful feature of Ansible is the set_fact module, which enables you to create or modify variables dynamically during playbook execution. It is part of the ansible.builtin collection.
Links
- [ansible.builtin.set_fact](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/set_fact_module.html)
Demo
In this article, we will explore the set_fact module and its usage through a practical example. We will Playbooknstrate how to retrieve the latest kernel package from a CentOS repository using Ansible's uri module and store it in a variable called kernel. Let's dive into the code example:
``yaml
---
- name: Regex Playbook
hosts: all
vars:
centos_repo: http://mirror.centos.org/centos/7/os/x86_64/Packages/
tasks:
- name: Get Latest Kernel
ansible.builtin.uri:
url: "{{ centos_repo }}"
method: GET
return_content: true
body_format: json
register: available_packages
- name: Save
ansible.builtin.set_fact:
kernel: "{{ available_packages.content | ansible.builtin.regex_replace('<.?>') | regex_findall('kernel-[0-9].rpm') }}"
- name: Print
ansible.builtin.debug:
var: kernel
`
Let's break down this playbook step by step to understand its functionality:
1. The name directive gives our playbook a descriptive title, "regex Playbook."
2. The hosts directive specifies the target hosts on which the playbook will be executed. In this case, it's set to all, meaning it will apply to all hosts in the inventory.
3. The vars section allows us to define variables used within the playbook. Here, we set the centos_repo variable to the URL of the CentOS 7 package repository.
4. The tasks section contains the actual work to be performed. We have three tasks defined.
5. The first task, named "Get Latest Kernel," uses Ansible's uri module to send an HTTP GET request to the centos_repo URL. It retrieves the content of the repository in JSON format and stores it in the available_packages variable using the register directive.
6. The second task, named "Save," utilizes the set_fact module. It takes the content stored in available_packages and applies two filters consecutively. First, it uses the regex_replace filter from the ansible.builtin plugin to remove any HTML tags from the content. Then, it applies the regex_findall filter from the same plugin to extract the kernel package names matching the pattern "kernel-[0-9].\*rpm." The resulting list of kernel package names is stored in the kernel variable using the ansible.builtin.set_fact` module.
7. The third task, named "Print," uses Ansible'