Variables

Learn about Ansible variables, their different types, why we need them, and how to use them.

Ansible variables store dynamic values for a given environment.

In our playbook, it is an excellent practice to use variables to store all the dynamic values we need. By editing variables, we can reuse our code in the future, only parameterizing according to our business needs.

Impermissible variable names

Ansible allows all the combinations of letters and numbers in variable names. If we plan to use numbers, be aware that we can’t use them at the start of the variable names.

The four main limitations in variable names are shown in the table below:

Variable Name Limitations

Not Allowed

Example

White spaces

my var

Dots

my.var

Starting with numbers

1stvar

Containing special characters

myvar$1

In this lesson, we’re going to explore the following:

  • User-defined variables
  • Extra variables
  • Host and group variables
  • Array variables
  • Registered variables

User-defined variables

User-defined variables are the most popular and the most similar to other programming languages. The declaration is performed using the vars statement followed by a list of each variable and value. Core variable types are the ones permitted by Python, such as string, number, boolean, list, dictionary, and so on. We can easily retrieve the variable value in any part of our Ansible playbook specifying the variable name between double brackets, like this: {{ variable name }}.

The following variableprint.yml playbook declares a variable fruit, assigns the value apple, ...