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 variables types: how to use variables in ansible?

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 types: how to use variables in ansible?

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 variables types: how to use variables in ansible?

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”.

ansible variables types: how to use variables in ansible?

To view Ansible facts associated with your local system, execute the following command:

$ sudo ansible -m setup localhost

ansible variables types: how to use variables in ansible?

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 variables types: how to use variables in ansible?

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

vars:

command_to_run: "date"

tasks:

- name: Execute Command

ansible.builtin.shell: "{{ command_to_run }}"

register: command_output

- name: Display Command Output

ansible.builtin.debug:

msg: "Command output: {{ command_output.stdout }}"

In the above example:

name: Describes the name of the playbook, which is "Run Command on Localhost."

hosts: Specifies the target hosts for the playbook. Here, it's set to localhost, meaning the playbook will run on the local machine only.

connection: Indicates how Ansible connects to the target hosts. Setting it to local means that Ansible executes tasks directly on the control node, which is the local machine.

gather_facts: Controls whether Ansible should gather facts about the target hosts. It's set to no, indicating Ansible won't collect any facts.

vars: Defines variables specific to this playbook. It sets a variable named command_to_run with the value "date," representing a shell command to fetch the current date.

tasks: Contains the list of tasks that Ansible will execute.

name: Describes the purpose of the task, which is to execute a command and display its output.

ansible.builtin.shell: This task module executes shell commands on the target hosts. Here, it runs the command specified in the command_to_run variable.

register: Captures the output of the shell command for later use. The output is stored in command_output.

ansible.builtin.debug: This task module is used to print the debug messages. Here, it displays the output of the command captured in command_output.stdout.

After running this Ansible playbook, you will see the execution of the date command on the localhost and display the output, which is the current date and time.

ansible variables types: how to use variables in ansible?

Ansible Register Variables

The Ansible register module serves to store the output of a task in a variable. Typically, this involves executing a task on a remote host using modules like shell or command. Once the register module captures the task's output, it can be referenced in various contexts, such as conditional statements or printing the output.

Let's explore how register is applied to capture task output. In the provided playbook, the free command is executed on a local host. The register module captures the command's output, and then it's displayed on the standard output (stdout).

---

- name: Ansible Register Variable Example

hosts: localhost

tasks:

- name: Get Memory Usage

shell: "free"

register: memory_usage

- debug:

var: memory_usage.stdout

In this example:

The shell module is used to execute the free command, which displays information on memory usage. The output of the free command is captured by the register module and stored in the memory_usage variable.

The debug module then displays the captured output of the free command using the stdout attribute of the memory_usage variable.

This playbook will execute the free command on localhost, but you can specify it for all hosts in the inventory file and display the memory usage information captured from each host.

ansible variables types: how to use variables in ansible?

Conclusion

In this guide, we delved into Ansible variables, exploring how to define and reference them across different scenarios. By harnessing variables, you gain the ability to customize and parameterize your playbooks, enhancing flexibility and adaptability. 

Moreover, we outlined key best practices to streamline variable usage within Playbooks, ensuring smoother automation workflows and reducing complexity. We demonstrated how you can use different Ansible variable types in a playbook and run on your system. If you are using a remote hosting or VPS Linux server, you can use the above guidelines and use the Ansible variables on your Linux server.

To learn more about Ansible variables and explore further possibilities, we encourage you to consult the official Ansible documentation. There, you'll find comprehensive resources and additional insights into Ansible variables, empowering you to leverage this powerful feature to its fullest potential. Embrace the versatility of Ansible variables to optimize your automation strategies and drive efficiency across your infrastructure.

Blog