Ansible Curriculum
Variable Basics
Variable Sources
Variable Usage
On this page
Subtopic•Variable Basics

What Are Variables

In Ansible, hardcoding configuration values (such as IP addresses, directory paths, ports, or usernames) directly inside your tasks limits reusability. If you need to deploy the same configuration to a different environment, you would have to modify the playbook code.

To solve this, use Variables. A variable is a named storage placeholder that holds dynamic values. By replacing hardcoded parameters with variables, you can customize playbook runs for different hosts and environments without modifying the tasks.

In this guide, we will cover variable naming conventions, analyze variable scopes (global, play, and host scopes), and write a playbook to print variables.

Variable Scopes Hierarchy

Ansible variables are classified into three scopes:

Diagram

Variable Naming Rules

When naming variables, you must follow strict formatting rules:

  • Starting Characters: Variable names must start with a letter or an underscore. They cannot start with a number.
  • Allowed Characters: Can only contain letters, numbers, and underscores (e.g. http_port is valid, http-port or http.port are invalid).
  • Reserved Keywords: Avoid using reserved Ansible keywords (such as groups, hosts, playbook_dir, or role_path).

1. Playbook: Displaying Variables

Here is a playbook that defines variables at the play scope and prints their values using the debug module:

# Save this file as print_variables.yml
---
- name: Variable Basics Playbook
  hosts: all
  gather_facts: no
  
  vars:
    # Defining variables at the play scope
    app_port: 8080
    app_path: "/var/www/my_app"
    user_name: "deploy_user"

  tasks:
    - name: Display configured variables
      ansible.builtin.debug:
        msg: "Deploying app as '{{ user_name }}' on port {{ app_port }} in directory: {{ app_path }}"

Summary

Variables allow you to write reusable playbooks by replacing hardcoded values with dynamic placeholders. By following variable naming conventions and defining scopes, you can customize task execution parameters. In the next section, we will cover defining variables.

←Previous ModuleModules