Ansible Variables Types: How To Use Variables in Ansible?
Ansible variables are useful in managing variations across systems. This platform enables the execution of playbooks and tasks across multiple systems simultaneously using a single command. Variations among systems can be expressed by defining variables using YAML syntax, including lists and dictionaries.
These variables can be set in various places, such as command lines, reusable files or roles, inventory, or playbooks. Moreover, new variables can be generated during playbook runs by assigning task return values as variables.
In this guide, we will go through the concepts of Ansible variables, examining their usage, types, and functionality in detail.
What Is the Significance of Ansible Variables?
Ansible is a popular configuration management tool extensively used to manage multiple servers efficiently. It simplifies tasks such as server setup and application installation by automating processes.
With Ansible, you can easily handle a large number of remote servers and execute tasks sequentially from a central core node. This streamlines management tasks, enhances productivity, and ensures consistency across your infrastructure.
Variables in Ansible serve as powerful tools for simplifying the management of dynamic values throughout a project, reducing the likelihood of human errors. They offer a convenient means of handling variations and discrepancies across different environments and systems.
With variables, we gain the flexibility to define them in various locations, each with different precedence levels tailored to our specific needs. Additionally, Ansible allows us to register new variables directly within our playbooks by capturing the output of tasks, further enhancing customization options.
One notable type of variable in Ansible is Ansible facts, which provide valuable information retrieved from remote hosts. These facts, accessible through the ansible_facts variable, offer insights into various aspects of the target systems.
For instance, we can obtain details about the operating system distribution (ansible_distribution) and (ansible_version), information regarding host devices, the Python version used by Ansible (ansible_python_version), and the system architecture, among others. Leveraging Ansible facts enriches our projects by enabling informed decision-making and efficient automation workflows.
Ansible Variable Name Rules
Variables in Ansible are assigned by following specific guidelines dictating the naming conventions for variables.
- In Ansible, the variable name must start with either an uppercase or lowercase letter. For example, username, Saleprice, etc.
- Variables in Ansible contain letters (either uppercase or lowercase, or a combination thereof), underscores, and digits—for example, username, sale_price, foo23, etc.
- Certain strings or keywords are reserved for special functions and cannot be used as valid variable names. These include Playbook Keywords and Python keywords.
While not mandatory, it’s advisable to use simple and descriptive variable names. This practice simplifies your workflow within Ansible.
Types of Ansible Variables
There are several kinds of Ansible variables that you may define and use in a playbook in different ways.
- Simple Variables;
- Special Variables (Connection variables, magic variables, Ansible facts);
- Register Variables.
Ansible Simple Variables ()
The most basic usage of simple variables is to define a variable using a single value in the playbook YAML file.
Let us take a simple example of a playbook that prints a message.
—
– name: Example Playbook with Variables
hosts: all
gather_facts: false
vars:
greeting_message: “Hello, welcome to Ansible variables understanding!”
tasks:
– name: Display Greeting
debug:
msg: “{ greeting_message }”
In the playbook above, we demonstrated the use of simple Ansible variables:
name: Identifies the playbook and provides a description.
hosts: Specifies the target hosts where the tasks will be executed. In this case, we set all.
tasks: Contains a list of tasks to be executed on the specified hosts.
name: Describes the task.
greeting_message is a variable that contains the message “Hello, welcome to Ansible variables understanding!”.
debug: Specifies a module to use that prints messages for debugging purposes. The debug task displays the value of the greeting_message variable.
msg: Defines the message to be printed.
Run the playbook, and the geeting_message value will be displayed inside a msg.
Ansible Set Variables in Task
Ansible set variables are user-defined variables that you can define and assign values to within playbooks or roles. These variables are typically used to store information that may change depending on your environment or requirements. You can set variables at different levels of scope, such as globally, within a playbook, or a specific task. Let’s take an example:
—
– name: Set variables
hosts: localhost
tasks:
– name: Set user role variables
set_fact:
user_name: “supervisor”
user_permissions: “rwx”
– name: Display user variables
debug:
msg: “The user ‘{ user_name }’ has permissions ‘{ user_permissions }'”
Ansible Variables with Arrays and Loops
In Ansible, just like in programming languages, arrays are used to store collections of items that are related. These collections, called arrays, can contain multiple values of the same data type.
Let’s take an example of an Ansible playbook that uses variables containing arrays/lists and demonstrates how to loop through them:
—
– name: Example Playbook with Variable Arrays and Loops
hosts: all
gather_facts: false
vars:
fruits:
– apple
– banana
– orange
tasks:
– name: Display Fruits
debug:
msg: “The fruit is { item }”
loop: “{ fruits }”
In the playbook above, “fruits” is a variable containing an array/list of fruits. The loop directive is used to iterate over the fruits array. Inside the loop, the debug task displays each fruit using the item variable.
Ansible Special Variables
In Ansible, special variables are pre-defined variables that contain important information about the system, inventory, or the context of playbook execution. Ansible special variables are categorized into different types, like magic variables, connection variables, and Ansible facts. Their names are reserved, meaning you can’t define variables with the same names as these special ones.
Ansible Facts
Ansible facts are details collected about the hosts during playbook execution. This process, termed gathering facts, involves obtaining information like the system’s IP address, current date and time, BIOS specifications, disk partitions, and other pertinent hardware details.
In this example:
We set gather_facts to true, which tells Ansible to collect information about the target hosts.
We then use the debug module to display some of the gathered facts, such as hostname (ansible_hostname), distribution (ansible_distribution) and its version (ansible_distribution_version), and total memory (ansible_memtotal_mb).
When you run this playbook with ansible-playbook, Ansible will gather facts from all the hosts specified in your inventory file and display the relevant information for each host. Here, we gather information only for “localhost”.
To view Ansible facts associated with your local system, execute the following command:
$ sudo ansible -m setup localhost
The above command uses the setup module to gather facts about the “localhost” system. It prints a JSON-formatted output containing a wide range of information about the local system, such as hardware details, network configuration, operating system, and more.
Ansible Magic Variables
Ansible magic variables are predefined variables that provide information about the execution environment, current host, or other contextual details. Magic variables in Ansible are generated automatically by the tool and are immutable, meaning users cannot modify their values. These variables always represent the internal state of Ansible and cannot be altered by users. Therefore, they are only usable in their predefined form and cannot be customized.
Here’s an example of how to use Ansible magic variables inside a playbook:
—
– hosts: all
tasks:
– debug:
var: ansible_version
Ansible Connection Variables
Connection variables in Ansible serve as configuration settings dictating how Ansible establishes connections with remote hosts during the execution of tasks and playbooks. They offer adaptability in managing diverse connection types, authentication mechanisms, and host-specific configurations.
Let’s take an example where we run the date command on localhost.
—
– name: Run Command on Localhost
hosts: localhost
connection: local
gather_facts: no