Installing Ansible and exploring the gather_facts option
Let's start by installing Ansible and exploring what the gather_facts
option does. In this step, we'll install Ansible, create a simple inventory, and run a command to see what facts are gathered.
Installing Ansible
First, let's install Ansible on our system:
sudo apt update
sudo apt install -y ansible
After installation completes, verify that Ansible is installed correctly:
ansible --version
You should see output similar to this:
ansible [core 2.12.x]
config file = /etc/ansible/ansible.cfg
configured module search path = ['/home/labex/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python3/dist-packages/ansible
ansible collection location = /home/labex/.ansible/collections:/usr/share/ansible/collections
executable location = /usr/bin/ansible
python version = 3.10.x (default, Aug 14 2022, 00:00:00) [GCC 11.2.0]
jinja version = 3.0.3
libyaml = True
Creating a simple inventory
Now, let's create a simple inventory file to work with. The inventory file defines the hosts that Ansible will manage. For this lab, we'll create a local inventory:
mkdir -p ~/project/ansible
cd ~/project/ansible
Create an inventory file named hosts
using the editor:
- Click on the Explorer icon in the WebIDE
- Navigate to the
/home/labex/project/ansible
directory
- Right-click and select "New File"
- Name the file
hosts
- Add the following content:
[local]
localhost ansible_connection=local
This inventory sets up a group called local
with only one host - localhost
. The ansible_connection=local
parameter tells Ansible to execute commands directly on the local machine without using SSH.
Exploring gather_facts
Let's run a simple Ansible command to see what facts are gathered by default:
cd ~/project/ansible
ansible local -i hosts -m setup
The command above uses:
local
: the group from our inventory
-i hosts
: specifies our inventory file
-m setup
: runs the setup module, which gathers facts
You'll see a large JSON output with detailed information about your system, including:
- Hardware information (CPU, memory)
- Network configuration
- Operating system details
- Environment variables
- And much more
This information is what Ansible collects when gather_facts
is enabled (which is the default behavior). These facts can be used in playbooks to make decisions or customize tasks based on the target system's characteristics.