Difficulty: Beginner
Estimated Time: 5-10 minutes

In this scenario, you'll learn how to use variables in ansible. We will create inline variables and using inventory files.

Summarizing what we learned:

  • How to use variables defined in inventory
  • How to use inline variables defined in playbook
  • How to use variables defined in file

Don’t stop now! The next scenario will only take about 10 minutes to complete.

Ansible Variables

Step 1 of 3

Step 1 - Variables Defined in Inventory

In this step, we will learn how to define variables in inventory.

Copy following YAML to playbook which will create new file on the localhost.

  name: Create file using inventory defined variable
  hosts: localhost
      name: Create file using inventory defined variable
      command: touch '{{ file_name }}'

This playbook will run touch command to create a new file in the current directory.

Inventory File

Create an inventory file and define variable file_name. echo "localhost ansible_connection=local file_name=test1" > inventory.txt

Now, run the playbook with the inventory file:

Run the playbook with ansible-playbook command: ansible-playbook -i inventory.txt playbook.yml


You can verify that file named test1 was created by listing the contents of the current directory ls.