Skip to main content

Working with Variables

1. Defining Playbook Variables

Variable Type Definition Usage Example Notes
host vars Variables defined for a specific host ansible_host: 192.168.1.10 Defined in inventory or host vars file
group vars Variables for a group of hosts http_port: 80 Defined in group vars file or inventory
play vars Variables defined in the play app_version: "2.3" Available only within the play scope
extra vars Variables passed at runtime via CLI ansible-playbook site.yml -e "env=prod" Overrides all other variable sources
role vars Variables defined in a role's vars directory database_port: 5432 Available within the role scope

Example: Defining Variables in a Playbook

---
- hosts: webservers
  vars:
    http_port: 80
    https_port: 443
    app_version: "2.3"
  tasks:
    - name: Ensure web server is running
      ansible.builtin.service:
        name: httpd
        state: started
        port: "{{ http_port }}"

2. Using Variable Files

File Type Extension Description Usage
vars.yml .yml YAML format for variables Used in vars section of playbooks or roles
vars.json .json JSON format for variables Used in vars section of playbooks or roles
group_vars/ /group_vars/group_name.yml Group-specific variables Automatically loaded for matching groups
host_vars/ /host_vars/host_name.yml Host-specific variables Automatically loaded for matching hosts

Example: vars.yml content

app_port: 8080
app_host: "localhost"
ssl_enabled: true

Example: Using vars file in playbook

- name: "Deploy application"
  hosts: web_servers
  vars_files:
    - vars.yml
  tasks:
    - name: "Start app server"
      command: "./start.sh --port {{ app_port }}"
Note: Variable files are loaded in order of precedence: host_vars > group_vars > playbook vars files.

3. Setting Host Variables

Variable Type Description Example
host_vars Variables specific to a particular host ansible_host: 192.168.1.10
group_vars Variables for a group of hosts ansible_user: ubuntu
inventory_vars Variables defined in inventory file ansible_connection: ssh

Example: Setting Host Variables in Inventory

[webservers]
web1 ansible_host=192.168.1.10 ansible_user=ubuntu
web2 ansible_host=192.168.1.11 ansible_user=ubuntu

[webservers:vars]
ansible_connection=ssh
ansible_become=true
Note: Host variables take precedence over group variables in Ansible.

4. Setting Group Variables

Variable Type Definition Scope Usage Example
group_vars/ Directory containing variable files for specific groups Group-level group_vars/webserver.yml
host_vars/ Directory containing variable files for specific hosts Host-level host_vars/web01.yml
inventory variables Variables defined in inventory files Inventory-level [webserver:vars] port=80

Example: Setting Group Variables in group_vars

---
# group_vars/webserver.yml
http_port: 80
ssl_enabled: true
ssl_cert_path: "/etc/ssl/certs"

Example: Using Group Variables in Playbook

---
- name: Configure web servers
  hosts: webserver
  tasks:
    - name: Ensure web server listens on correct port
      uri:
        url: "http://localhost:{{ http_port }}"
        status_code: 200

5. Using Extra Variables

Variable Type Description Usage
--extra-vars Pass variables from the command line ansible-playbook site.yml --extra-vars "max_workers=10"
--extra-vars file.json Load variables from a JSON file ansible-playbook site.yml --extra-vars @vars.json
--extra-vars file.yml Load variables from a YAML file ansible-playbook site.yml --extra-vars @vars.yml

Example: Setting Variables from CLI

ansible-playbook deploy.yml --extra-vars "environment=prod region=us-west-1"

Example: Using JSON File for Extra Vars

{
  "app_name": "myapp",
  "version": "1.2.3"
}
ansible-playbook deploy.yml --extra-vars @app_vars.json
Note: Extra variables override inventory and group variables in the playbook.

6. Registering Variables

Property Description Example
register Stores the result of a task in a variable for later use
- name: Get system info
  command: uname -a
  register: system_info
delegate_to Runs the task on a different host than the one specified in the playbook
- name: Run on specific host
  command: whoami
  delegate_to: webserver1

Example: Using Registered Variables

- name: Capture output of a command
  command: echo "Hello World"
  register: output

- name: Use the registered variable
  debug:
    msg: "The command output was: {{ output.stdout }}"

- name: Use registered variable in a loop
  debug:
    msg: "Line {{ item }}: {{ output.stdout_lines[item] }}"
  loop: "{{ range(0, output.stdout_lines | length) }}"
Note: Registered variables are available throughout the playbook and can be used in conditionals, loops, and other tasks.

7. Setting Facts

Property Description Example
ansible_facts Dictionary of facts collected by Ansible
{
  "ansible_os_family": "RedHat",
  "ansible_distribution": "CentOS"
}
set_fact Module to set custom facts in a playbook
- name: Set custom fact
  set_fact:
    my_var: "value"

Example: Setting a Fact in a Playbook

- name: Set custom facts
  hosts: all
  tasks:
    - name: Set environment variable
      set_fact:
        env: "production"
        app_version: "2.1.0"
Note: Facts set with set_fact are available for the remainder of the playbook run.

8. Accessing Variables

Variable Type Access Syntax Description
Host Variables hostvars[inventory_hostname] Access variables defined for a specific host
Group Variables group_names List of groups a host belongs to
Facts ansible_facts System information gathered by setup module
Registered Variables register Store command output in a variable
Loop Variables item Current item in a loop iteration
Environment Variables env.VAR_NAME Access environment variables in playbook

Example: Accessing Host Variables

- name: Access host-specific variables
  debug:
    msg: "Host {{ inventory_hostname }} has IP {{ hostvars[inventory_hostname].ansible_host }}"

Example: Using Facts

- name: Display OS information
  debug:
    msg: "OS is {{ ansible_facts.os_family }} version {{ ansible_facts.kernel }}"

Example: Loop with Item Variable

- name: Process list of files
  copy:
    src: "{{ item }}"
    dest: "/tmp/{{ item }}"
  loop:
    - file1.txt
    - file2.txt
Note: Use hostvars to access variables from other hosts in the inventory.
Warning: Avoid using hostvars in templates as it can cause performance issues.

9. Using Variable Syntax

Variable Type Syntax Description
Host Variables hostvars[inventory_hostname] Access variables defined for a specific host
Group Variables group_names List of groups a host belongs to
Facts ansible_facts System information gathered by Ansible
Registered Variables register Store command output in a variable
Loop Variables item Current item in a loop iteration

Example: Using Host Variables

- name: Access host-specific variable
  debug:
    msg: "Host IP is {{ hostvars[inventory_hostname].ansible_host }}"

Example: Using Facts

- name: Display OS information
  debug:
    msg: "OS is {{ ansible_facts.os_family }} and version is {{ ansible_facts.kernel }}"

Example: Using Registered Variables

- name: Store command output
  command: whoami
  register: user_output

- name: Use stored output
  debug:
    msg: "Current user is {{ user_output.stdout }}"

10. Accessing Nested Variables

Variable Path Type Description
hostvars['hostname']['variable_name'] Host Variable Access variables set on a specific host
group_vars['group_name']['variable_name'] Group Variable Access variables defined in group vars files
hostvars['hostname']['nested']['key'] Nested Host Variable Access nested dictionary values from host variables
inventory_hostname Inventory Variable Current host's name in the inventory

Example: Accessing Nested Variables in a Playbook

- name: Access nested variables
  hosts: webservers
  tasks:
    - name: Print nested variable value
      debug:
        msg: "Database port is {{ hostvars[inventory_hostname]['database']['port'] }}"

11. Understanding Variable Precedence

Source Priority Description
Command line values 10 Values set via -e or --extra-vars
Role defaults 9 Default values defined in roles
Inventory variables 8 Variables defined in inventory files
Group vars 7 Variables defined in group_vars/ directories
Host vars 6 Variables defined in host_vars/ directories
Playbook vars 5 Variables defined in the playbook itself
Include vars 4 Variables included via include_vars
Set fact variables 3 Variables set via set_fact
Role vars 2 Variables defined in roles
Playbook defaults 1 Default values defined in playbooks

Example: Variable Precedence in Playbook

- hosts: all
  vars:
    app_port: "8080"
  tasks:
    - name: Debug variable
      debug:
        msg: "Port is {{ app_port }}"
Note: Command line values override all other variables, making them the highest priority in the variable precedence hierarchy.

12. Providing Default Values

Variable Default Value Description
ansible_facts {} Dictionary of facts collected from the managed nodes
ansible_playbook_dir /path/to/playbook Directory where the playbook is located
ansible_inventory_dir /path/to/inventory Directory containing the inventory file
ansible_user root Default user to connect as when running tasks
ansible_connection ssh Connection method to use (e.g., ssh, local)

Example: Setting Default Values in a Playbook

---
- hosts: all
  vars:
    ansible_user: "admin"
    ansible_connection: "ssh"
  tasks:
    - name: Display default user
      debug:
        msg: "User is {{ ansible_user }}"

Was this article helpful?