In this beginner-friendly lab, you will learn how to use Ansible to gather facts about your managed hosts and display specific information. Specifically, you will create a playbook to display the number of CPUs on the target host.
- Understand how to gather facts in Ansible.
- Access and use gathered facts in tasks.
- Create a task to display the CPU count of a target host.
- Basic understanding of YAML syntax.
- Ansible installed on your ansible machine.
- Access to one or more hosts configured for management with Ansible.
Estimated Time: 20 minutes
-
On your ansible machine, open a text editor and create a new file named
cpu_count_playbook.yml
. -
Start defining your playbook with the following content:
--- - name: Display CPU count hosts: servers gather_facts: yes
Explanation:
hosts: servers
specifies that the playbook should run on hosts in theservers
group.gather_facts: yes
enables Ansible to collect information about the host before executing tasks.
-
Under the
tasks
section, add a task to display the number of CPUs:tasks: - name: Display CPU count debug: msg: "The target host has {{ ansible_processor_vcpus }} CPUs."
Explanation:
- This task uses the
debug
module to print a message. {{ ansible_processor_vcpus }}
is a variable provided by Ansible's gathered facts, representing the number of CPUs on the host.
- This task uses the
-
Save the
cpu_count_playbook.yml
file. -
Execute the playbook using the following command:
ansible-playbook cpu_count_playbook.yml
-
Observe the output. The playbook will display the number of CPUs for each host in the
servers
group.
Congratulations! You've successfully created an Ansible playbook that gathers facts about your hosts and displays the number of CPUs. This exercise demonstrates how to access and use the information collected by Ansible, a fundamental skill for more advanced automation tasks. Keep experimenting with different facts to explore what information you can gather and utilize. 👏