This article explores how to define and use variables in Ansible playbooks and inventory files for flexibility and scalability.
In this lesson, we will explore how variables work in Ansible. Variables in Ansible serve the same purpose as in other scripting or programming languages: they store dynamic values that can differ between systems or tasks. For instance, when applying patches with a single playbook to hundreds of servers, variables provide unique information such as hostnames, usernames, or passwords for each server.
Previously, we encountered variables within the inventory file. In the example below, variables define settings such as the Ansible host, connection type, and SSH password:
Variables can also be declared directly within a playbook. Consider the following playbook that adds a DNS entry to the /etc/resolv.conf file. Here, the variable dns_server is defined using the vars directive:
Copy
Ask AI
- name: Add DNS server to resolv.conf hosts: localhost vars: dns_server: 10.1.250.10 tasks: - lineinfile: path: /etc/resolv.conf line: "nameserver 10.1.250.10"
However, the above playbook contains a hard-coded IP address. To improve its flexibility, replace the fixed IP with the variable dns_server using Jinja2 templating. Simply enclose the variable name in double curly braces:
Copy
Ask AI
- name: Add DNS server to resolv.conf hosts: localhost vars: dns_server: 10.1.250.10 tasks: - lineinfile: path: /etc/resolv.conf line: "nameserver {{ dns_server }}"
Consider a playbook for configuring a firewall. The playbook below sets various firewall rules. However, many values are hard-coded, making it difficult to reuse the playbook in different scenarios:
A more flexible approach is to move these values into the inventory or a dedicated variables file. When using the inventory file, the playbook refers to variables using Jinja2 templating. Modifying the inventory file alone updates the playbook’s behavior without editing the playbook itself. An even more organized strategy is to store host-specific variables in a file such as web.yml, ensuring these values are automatically available when the playbook runs.
When incorporating a variable into a string, enclose it within quotes if the variable appears at the beginning. However, if it appears in the middle of the string, quotes are not strictly necessary.
Below is an updated example of the firewall configuration playbook using variables:
In this lesson, we learned how to define and use variables in Ansible playbooks and inventory files. By leveraging Jinja2 templating, you can create more flexible, maintainable, and scalable playbooks. Now, let’s proceed to the exercises and practice working with variables in various coding challenges.For more details about Ansible and best practices, be sure to check the Ansible Documentation.