Skip to main content

Implementing Variables and Facts in Playbooks

Ansible is a powerful configuration management tool that can handle complex deployments. One of its key features is the ability to use variables and facts, which can greatly simplify the task of managing multiple systems. In this tutorial, we will dive into implementing variables and facts in Ansible playbooks.

Understanding Variables

Variables in Ansible provide a convenient way to manage and control the actions of tasks. Let's look at an example:

---
- hosts: webservers
vars:
http_port: 80
max_clients: 200
tasks:
- name: ensure apache is at the latest version
yum:
name: httpd
state: latest
- name: write the apache config file
template:
src: /srv/httpd.j2
dest: /etc/httpd.conf
notify:
- restart apache
- name: ensure apache is running
service:
name: httpd
state: started

In the above playbook, 'http_port' and 'max_clients' are variables. These variables can be used throughout the playbook, and are particularly useful in templates.

Implementing Variables in Tasks

Variables can be used in tasks for a variety of reasons. For example, you might want to use a variable to define the source and destination of a file:

- name: Template a file
template:
src: "{{ source_file }}"
dest: "{{ destination_file }}"

Understanding Facts

Facts in Ansible are global variables that contain information about the system, like network interfaces or operating system. Facts are automatically discovered by Ansible when running tasks. Here is how you can use facts:

- name: Display the IP address
debug:
var: ansible_default_ipv4.address

Implementing Facts in Tasks

Facts can be used in tasks to gather information about the system. For example, you might want to know the distribution of the operating system:

- name: Display the OS distribution
debug:
var: ansible_distribution

Combining Variables and Facts

Variables and facts can be combined in tasks to perform more complex actions. For example, you might want to install a package only if the operating system is CentOS:

- name: Install htop on CentOS
yum:
name: htop
state: present
when: ansible_distribution == 'CentOS'

In the above task, the package 'htop' is only installed if the operating system is CentOS, as determined by the fact 'ansible_distribution'.

Conclusion

Variables and facts are crucial elements in Ansible playbooks. They provide a flexible way to manage and control tasks, whether you are deploying to a single machine or a cluster of servers. By understanding and implementing variables and facts, you can write more efficient and adaptable playbooks.