Introduction to Variables and Facts in Ansible
1. What are Variables in Ansible?
Variables in Ansible provide a way to store and manipulate data that can be used throughout your playbooks and roles. They allow you to create dynamic and reusable automation scripts. Variables can be defined in multiple places and have a specific precedence order.
2. Defining Variables
Variables can be defined in various ways in Ansible, including in playbooks, inventory files, and variable files. Here’s an example of defining a variable in a playbook:
--- - hosts: webservers vars: http_port: 80 tasks: - name: Ensure HTTP port is correct debug: msg: "The HTTP port is {{ http_port }}"
3. Using Variables
Variables can be used in playbooks to make them more dynamic. You can reference a variable by using the double curly braces {{ variable_name }}
. Here is an example:
--- - hosts: webservers vars: http_port: 80 tasks: - name: Open HTTP port firewalld: port: "{{ http_port }}/tcp" permanent: true state: enabled become: true
4. What Are Facts in Ansible?
Facts in Ansible are pieces of information about the remote systems that are gathered when a playbook runs. These facts provide details about the system, such as IP addresses, operating system, and hardware information. Facts are gathered automatically by Ansible using the setup
module.
5. Gathering Facts
Facts are gathered by default at the start of the playbook execution. You can also gather facts manually using the setup
module. Here is an example:
--- - hosts: all tasks: - name: Gather facts setup: - name: Display all facts debug: var: ansible_facts
6. Accessing Facts
Facts can be accessed using the ansible_facts
variable. You can access specific pieces of information from the facts dictionary. Here’s an example:
--- - hosts: all tasks: - name: Print operating system debug: msg: "The operating system is {{ ansible_facts['os_family'] }}"
7. Custom Facts
In addition to the built-in facts, you can also create custom facts. Custom facts can be created by placing JSON or INI formatted files in the /etc/ansible/facts.d
directory on the remote system. Here’s an example of a simple custom fact:
[custom] favorite_color=blue
You can then access this custom fact in your playbooks:
--- - hosts: all tasks: - name: Display custom fact debug: msg: "The favorite color is {{ ansible_facts['custom']['favorite_color'] }}"
Conclusion
Understanding how to use variables and facts is essential for writing effective Ansible playbooks. Variables help you create dynamic and flexible playbooks, while facts provide valuable information about your managed systems. By mastering these concepts, you can create more powerful and efficient automation scripts.