Working with Host and Group Variables
1. Defining Host Variables
| Variable Name | Definition Method | Scope | Notes |
|---|---|---|---|
| ansible_host | inventory.hosts['hostname'].ansible_host = '192.168.1.10' |
Host-specific | Overrides default inventory hostname |
| ansible_port | inventory.hosts['hostname'].ansible_port = 22 |
Host-specific | SSH port for connection |
| ansible_user | inventory.hosts['hostname'].ansible_user = 'admin' |
Host-specific | User for SSH connection |
| ansible_become | inventory.hosts['hostname'].ansible_become = true |
Host-specific | Enable privilege escalation |
| ansible_ssh_private_key_file | inventory.hosts['hostname'].ansible_ssh_private_key_file = '/path/to/key' |
Host-specific | SSH private key file path |
Example: Setting Host Variables in Inventory
[webservers]
web1 ansible_host=192.168.1.10 ansible_user=admin ansible_port=2222
web2 ansible_host=192.168.1.11 ansible_user=admin ansible_port=2222
[database]
db1 ansible_host=192.168.1.20 ansible_user=root ansible_port=22
Example: Using Host Variables in Playbook
- name: Configure Web Servers
hosts: webservers
tasks:
- name: Set server port
set_fact:
server_port: "{{ ansible_port }}"
- name: Display host info
debug:
msg: "Connecting to {{ ansible_host }} on port {{ ansible_port }}"
2. Defining Group Variables
| Variable Type | Definition Method | File Location | Notes |
|---|---|---|---|
| Group Vars | YAML or JSON files | group_vars/<group_name>.yml |
Variables specific to a group of hosts |
| Group Vars | YAML or JSON files | group_vars/<group_name>.json |
Same as above but in JSON format |
Example: Defining Group Variables in YAML
---
# File: group_vars/web_servers.yml
http_port: 80
https_port: 443
ssl_enabled: true
Example: Defining Group Variables in JSON
{
"http_port": 80,
"https_port": 443,
"ssl_enabled": true
}
3. Setting Connection Variables
| Variable | Values | Description |
|---|---|---|
| ansible_connection | ssh, local, winrm |
Connection type to use for the host or group |
| ansible_host | hostname, ip.address |
Host or IP address to connect to |
| ansible_port | 22, 5985 |
Port to connect to on the target host |
| ansible_user | username |
User to connect as |
| ansible_password | password |
Password for authentication (not recommended) |
| ansible_ssh_private_key_file | ~/.ssh/id_rsa |
Path to SSH private key file |
| ansible_become | yes, no |
Use privilege escalation (sudo/su) |
| ansible_become_method | sudo, su |
Privilege escalation method to use |
Example: Setting SSH connection variables for a group
all:
hosts:
webserver:
ansible_host: 192.168.1.10
ansible_user: deploy
ansible_port: 2222
ansible_ssh_private_key_file: ~/.ssh/deploy_key
Example: Using become with a different user
web_servers:
hosts:
web1:
ansible_host: web1.example.com
ansible_user: deploy
ansible_become: yes
ansible_become_method: sudo
ansible_become_user: root
4. Using Behavioral Parameters
| Parameter | Description | Values | Notes |
|---|---|---|---|
| ansible_connection | Connection type to use for the host | ssh, local, winrm |
Default is ssh for most Unix-like systems |
| ansible_user | User to connect as | String | Defaults to the user specified in inventory or ansible_user in group vars |
| ansible_port | Port to connect to | 22 (default for SSH) |
Can be overridden in inventory or group vars |
| ansible_become | Use privilege escalation | true, false |
Requires ansible_become_method to be set |
| ansible_become_method | Privilege escalation method | sudo, su, doas |
Defaults to sudo if not specified |
| ansible_become_user | User to become when escalating privileges | String | Defaults to root if not specified |
| ansible_shell_executable | Shell to use for execution | Path to shell executable | Useful when the default shell is not available or not preferred |
| ansible_python_interpreter | Python interpreter to use | Path to Python executable | Useful for systems with multiple Python versions or non-standard paths |
Example: Setting behavioral parameters in inventory
[webservers]
web1 ansible_host=192.168.1.10 ansible_user=deploy ansible_become=true ansible_become_method=sudo ansible_python_interpreter=/usr/bin/python3
[database]
db1 ansible_host=192.168.1.20 ansible_user=root ansible_become=true ansible_become_method=doas ansible_shell_executable=/bin/bash
Example: Using behavioral parameters in group vars
# group_vars/webservers.yml
ansible_user: deploy
ansible_become: true
ansible_become_method: sudo
ansible_python_interpreter: /usr/bin/python3
# group_vars/database.yml
ansible_user: root
ansible_become: true
ansible_become_method: doas
ansible_shell_executable: /bin/bash
5. Setting Privilege Escalation
| Option | Values | Description |
|---|---|---|
| become | true |
Enable privilege escalation for the task |
| become_method | sudo |
Method used to escalate privileges (e.g., sudo, su, doas) |
| become_user | root |
User to escalate privileges to (default is root) |
| become_flags | -Hs |
Flags passed to the privilege escalation method (e.g., -Hs for sudo) |
Example: Using become with sudo
- name: Install a package with elevated privileges
apt:
name: nginx
state: present
become: true
become_method: sudo
become_user: root
Note: Privilege escalation requires appropriate permissions on the target host. Ensure that the user running the playbook has the necessary rights to escalate privileges.
6. Understanding Variable Precedence
| Variable Source | Precedence Level | Description |
|---|---|---|
| CLI variables | 1 |
Variables passed via command line using --extra-vars |
| Host variables | 2 |
Variables defined directly on a host in inventory or external sources |
| Group variables | 3 |
Variables defined for a group in inventory or external sources |
| Host group variables | 4 |
Variables defined for a group that includes a host |
| Playbook variables | 5 |
Variables defined in the playbook itself (e.g., vars section) |
| Role variables | 6 |
Variables defined in a role's defaults/main.yml or vars/main.yml |
| Facts | 7 |
Automatically gathered system information (e.g., ansible_facts) |
| Inventory variables | 8 |
Variables defined in inventory files (e.g., host_vars/, group_vars/) |
| Role parameters | 9 |
Variables passed to a role via role in a playbook |
| Set facts | 10 |
Variables set dynamically using set_fact |
| Environment variables | 11 |
Variables set in the environment (e.g., ANSIBLE_...) |
| Configuration variables | 12 |
Variables from ansible.cfg or ANSIBLE_... environment variables |
Example: Variable Precedence in Playbook
- hosts: all
vars:
app_port: 8080
tasks:
- name: Debug variable precedence
debug:
msg: "Port is {{ app_port }}"
Note: The precedence order ensures that CLI variables override all others, and configuration variables are the lowest priority.
7. Using all and ungrouped Groups
| Group | Description | Usage |
|---|---|---|
| all | The default group that includes all hosts defined in inventory | Used to define variables available to every host |
| ungrouped | Contains hosts that are not assigned to any group | Hosts without explicit group assignment fall into this group |
Example: Defining variables for all hosts
all:
vars:
ansible_user: "admin"
ansible_ssh_private_key_file: "/path/to/private/key"
8. Setting Group Priority
| Property | Description | Default Value | Notes |
|---|---|---|---|
| ansible_group_priority | Defines the priority of a group when determining variable precedence | 0 |
Higher values take precedence over lower values. Groups with the same priority are processed in alphabetical order. |
Example: Setting Group Priority in Inventory
[webservers]
host1 ansible_group_priority=20
[production]
host2 ansible_group_priority=30
[all:vars]
ansible_group_priority=10
Note: The
ansible_group_priority variable is used to control the order in which groups are processed when determining variable precedence. Groups with higher priority values will override variables from groups with lower priority values.
9. Merging Variables
| Variable Source | Merge Behavior | Notes |
|---|---|---|
| host_vars/hostname.yml | merge |
Merges with group vars and play vars |
| group_vars/groupname.yml | merge |
Merges with play vars |
| playbook.yml (vars) | merge |
Merges with inventory vars |
Example: Merging Host and Group Variables
---
- hosts: all
vars:
common_var: "from_playbook"
merged_data:
key1: "playbook_value"
key2: "playbook_override"
tasks:
- name: Display merged variables
debug:
msg: "common_var={{ common_var }} merged_data={{ merged_data }}"
Note: When merging, nested dictionaries are merged recursively, while lists are replaced entirely.
10. Organizing Variable Files
Example: Directory Structure for Variables
ansible/
├── group_vars/
│ ├── all.yml
│ ├── webservers.yml
│ └── databases.yml
├── host_vars/
│ ├── web1.example.com.yml
│ └── db1.example.com.yml
└── vars/
├── common.yml
└── roles/
└── webapp/
└── vars/
└── main.yml
| Directory | Description | Scope | Usage |
|---|---|---|---|
| group_vars/ | Variables specific to groups of hosts | Group-level | Define variables for entire groups (e.g., webservers.yml) |
| host_vars/ | Variables specific to individual hosts | Host-level | Define variables for specific hosts (e.g., web1.example.com.yml) |
| vars/ | General variable files | Playbook-level | Define variables for use in playbooks or roles |
Note: The
group_vars/ and host_vars/ directories are automatically scanned by Ansible for variable definitions. Variables in group_vars apply to all hosts in the group, while host_vars override any group or global variables for that specific host.Best Practices
- Use
group_vars/to define common variables for groups of hosts (e.g.,webservers.yml). - Use
host_vars/to override or define host-specific variables (e.g.,web1.example.com.yml). - Organize variables in
vars/or role-specific directories for clarity and reusability. - Use YAML files with
.ymlor.yamlextensions for variable files.