Ansible: Working with Variables and Hostvars

When I started to write about my infrastructure@home project, Ansible became the central configuration management tool. In order to be more effective with Ansible, I started to read the books Ansible Up and Running and Mastering Ansible. I learned a lot more about Ansible then what is necessary for the project, but those things are interesting in itself and I want to share them in a tutorial style. This is the first article.

In this article, we will learn what host facts are and how to see them, and we will now learn how to define variables from task execution.

This article originally appeared at my blog.

Gather and Display Host Fact

Each time Ansible executes a task, the first step is to collect facts about nodes. These facts can be access with the hostvars variable. Let’s write a playbook that prints the hostvars for each node.

We will execute this playbook only for the node raspi-4-1.

The output only shows an excerpt of the variables. As you can see, Ansible retrieves facts about the operating system, the hardware architecture, memory and cpu, and IP addresses. There are interesting use cases to access and use this information, for example you can collect the ip addresses of the hosts and use them to create a Nginx config file.

You can also execute this command as an ad-hoc task:

Once you are familiar with the facts, you can quickly query a node by using the following command:

Define and use variables

Lets write a playbook that retrieves the hostname of our nodes. We open the playbook tutorial_retrieve_hostname.yml and write the following:

When we execute this playbook, we can see the following output:

The command works, but we did not see any output. How can we store the return value of the command? We need to save the result of the hostname command in a variable, and then we need to print this variable to the console:

Let’s execute this playbook:

What happens here? We see a lot more than expected! Each Ansible module returns a data structure that includes information like time, return code, task failed and more. However, we are specifically interested into the value stdout. Also, we want to store this variable as a fact of the host with the set_fact module. Then, this variable will be available in all subsequent tasks throughout the playbook.

Here is this version:

Let’s see the output of this playbook:

Exactly what we wanted.


Ansible collects a lot of useful facts about the hosts. In this article, we learned how to access and print them. We also learned how to capture tasks results in variables and store them as facts on the hosts during the execution of a playbook. Handling variables effectively is of key importance when working with Ansible.

IT Project Manager & Developer