Variables
Ansible supports variables that can be used to store values that can then be reused throughout files in an Ansible project.
Naming Variables
Variable names must start with a letter, and they can only contain letters, numbers, and underscores. For example web_server
.
Variables can be defined in a variety of places:
- Global scope
- Play scope
- Host scope
Defining Variables in Playbooks
A common method is to place a variable in a vars block at the beginning of a playbook:
Or to define playbook variables in external files:
Using Variables in Playbooks
When a variable is used as the first element to start a value, quotes are mandatory.
Host Variables and Group Variables
Use directories to populate host and group variables by creating two directories group_vars
and host_vars
.
Example structure:
ansible
├── ansible.cfg
├── group_vars
│ ├── dc1
├── host_vars
│ ├── server.example.com
├── inventory
└── playbook.yml
Overriding Variables from the Command Line
Inventory variables are overridden by variables set in a playbook, which in turn may be overridden through arguments passed to the ansible
or ansible-playbook
commands on the command line. Variables set on the command line are called extra variables.
Example:
Using Arrays as Variables
You cna also can use arrays, which are iterated over by ansible.
Example:
users:
bjones:
first_name: Joe
last_name: Blogs
home_dir: /users/jblogs
acook:
first_name: John
last_name: Doe
home_dir: /users/jdoe
These can be explicitly referenced like this:
Registered VariablesUse the register statement to capture the output of a command: