Variables
Notes// archive From the original Code Walker docs. Kept for reference, so some versions and commands may be out of date.
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:
- hosts: all
vars:
user: richard
home: /home/richardOr to define playbook variables in external files:
- hosts: all
vars_files:
- vars/packages.ymlUsing Variables in Playbooks
When a variable is used as the first element to start a value, quotes are mandatory.
vars:
user: richard
tasks:
- name: Create user {{ user }}
user:
name: "{{ user }}"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.ymlOverriding 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:
ansible-playbook main.yml -e "package=httpd"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/jdoeThese can be explicitly referenced like this:
users.jdoe.first_nameRegistered Variables
Use the register statement to capture the output of a command:
---
- name: Install a package
hosts: all
tasks:
- name: Install package
yum:
name: httpd
state: installed
register: install_result
- debug: var=install_result