Level 1
0 / 100 XP

Variable Files

In this lesson, you will learn about Ansible variable files, which are essential for managing and organizing variables in a more structured and readable manner. This concept is particularly useful when you have a large number of variables or when variables need to be shared across multiple playbooks. By the end of this lesson, you will know how to create a variable file and use it within your playbook.

Introduction to Variable Files

Variable files in Ansible are typically written in YAML format. They allow you to keep your variable data separate from your playbook, making your Ansible code cleaner and more maintainable. This separation is particularly useful when dealing with different environments (like development, testing, and production), each with its own specific configuration.

Creating a Variable File

To manage our variables for the webservers group, we'll start by creating a variable file named webservers_vars.yml. This is a straightforward process that involves using a text editor. In this case, we can use nano, a popular command-line text editor. Open nano by typing the following command:

nano ~/code/my_vars.yml

In the webservers_vars.yml file, we'll define a variable that specifies the path of the file we want to create on each managed node. The content of the variable file should look like this:

var_file_path: /tmp/vars_file_{{ ansible_hostname }}.txt

This YAML file defines a single variable var_file_path, which is a template string. The {{ ansible_hostname }} is a placeholder that Ansible replaces with the hostname of each managed node when the playbook is executed. By using this variable, we ensure that each host creates a file with its own hostname in the path, maintaining uniqueness across different nodes.

Using Variable Files in Playbooks

After creating the variable file, the next step is to incorporate it into our existing playbook, first_playbook.yml. We want Ansib…