Ansible Curriculum
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:
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_portis valid,http-portorhttp.portare invalid). - Reserved Keywords: Avoid using reserved Ansible keywords (such as
groups,hosts,playbook_dir, orrole_path).
1. Playbook: Displaying Variables
Here is a playbook that defines variables at the play scope and prints their values using the debug module:
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.