Level 1
0 / 100 XP

Playbook and Inventory Variables

In this lesson, you will explore the concept of variables in Ansible playbooks. Variables in Ansible are essential for creating flexible and reusable playbooks. They allow you to manage and use data that can change over time or across environments, such as user names, server addresses, or configuration settings. By the end of this lesson, you'll understand how to define, use, and manage variables within your playbooks.

Understanding Variables in Ansible

Variables in Ansible are similar to variables in programming languages; they are placeholders or references to data. The data can vary based on the context, environment, or conditions under which a playbook runs. Using variables makes your playbooks less static and more dynamic, enabling them to be used in various situations without changing the playbook code.

Variables can be defined in several places:

  • In the playbook itself: Directly within the playbook for specific hosts or tasks.
  • In inventory files: Grouped with certain hosts or groups in your inventory.
  • In separate files or roles: Organized in separate files for better structure and reusability.

Defining Variables in a Playbook

To define a variable in a playbook, you can include a vars section. Let's look at an example:

Text
--- - hosts: all vars: file_path: /tmp/sample_file_{{ ansible_hostname }}.txt tasks: - name: Create an empty file file: path: "{{ file_path }}" state: touch

In this example:

  • The variable file_path is defined under the vars section.
  • The file module uses file_path variable to create a file. The {{ file_path }} syntax is used to reference the variable.

Execute the Playbook

Now let's run the playbook using the ansible-playbook command:

ansible-playbook first_playbook.yml

Here is the output:

![ansible-playbook Run](https://zrftqtvkikjkbtkfalgp.s…