Dictionary variables hold a complex combination of key-value pairs, the same as a Python dictionary.

You can define dictionary variables using the standard YAML syntax, as in the following example:
foo:
bar: one
baz: two

There are two ways in which to refer to these variables’ values. For example, in dot notation, we can write the following:
bar: {{ foo.bar }}

And in bracket notation, we can depict the same thing using the following expression:
bar: {{ foo[bar] }}

We can use either dot or bracket notation in the same way as in Python.

Tip

While both dot and bracket notation signify the same thing, bracket notification is better. With dot notation, some keys can collide with the methods and attributes of Python dictionaries.

Now, let’s look at ways of sourcing variable values.

Sourcing variable values

While you can manually define variables and provide their values, sometimes we need dynamically generated values; for example, if we need to know the server’s hostname where Ansible is executing the playbook or want to use a specific value returned from a task within a variable. Ansible provides a list of variables and system metadata during the gathering facts phase for the former requirement. That helps determine which variables are available and how to use them. Let’s understand how we can gather that information.

Finding metadata using Ansible facts

Ansible facts are metadata information associated with the managed nodes. Ansible gets the facts during the gathering facts stage, and we can use the facts variable directly within the playbook. We can use the setup module as an Ansible task to determine the facts. For example, you can run the following command to get the Ansible facts for all nodes with the webservers role:

$ ansible -m setup webservers
web | SUCCESS => {
“ansible_facts”: {
“ansible_all_ipv4_addresses”: [
“10.0.2.5”
],

“ansible_hostname”: “web”,

So, as we can see, we get ansible_facts with multiple variables associated with the inventory item. As we have a single server here, we get web server details. Within the piece, we have an ansible_hostname attribute called web. We can use that ansible_hostname attribute within our playbook if we need to.

Sometimes, we want to source a task’s output to a particular variable to use the variable in any subsequent tasks of the playbook. Let’s look at how we can do that.

Leave a Reply

Your email address will not be published. Required fields are marked *