6-Day3-1-Variables
Lab Exercise: Types of Variables and Their Hierarchy
Objective:
Understand the variable precedence hierarchy in Ansible using group variables, host variables, play variables, task variables, and extra vars in a step-by-step manner.
Lab 1.1: Group Variables in Inventory
Scenario:
Define group variables in the inventory file and observe how they are resolved.
Steps:
Define Inventory with Group Variables:
Create
~/day3/inventory.iniwith the following content:[web_servers] web1 ansible_host=192.168.1.10 ansible_user=ec2-user web2 ansible_host=192.168.1.11 ansible_user=ec2-user [web_servers:vars] website_port=8080 website_content="Content from group variables"
Create the Playbook:
Save as
~/day3/group_variables.yaml:- name: Group Variables Demo hosts: web_servers tasks: - name: Display website_port from group variables debug: msg: "Website Port: {{ website_port }}" - name: Display website_content from group variables debug: msg: "Website Content: {{ website_content }}"
Run the Playbook:
Execute the playbook:
ansible-playbook ~/day3/group_variables.yaml -i ~/day3/inventory.ini
Expected Output:
The values of
website_portandwebsite_contentare resolved from the group variables in the inventory file.
Lab 1.2: Host Variables in Inventory
Scenario:
Add host variables to the inventory and observe how they override group variables.
Steps:
Modify the Inventory File:
Update
inventory.inito include host-specific variables:
Modify the Playbook (optional):
Use the same playbook
group_variables.yamlfrom Lab 1.1.
Run the Playbook:
Execute the playbook and observe the output:
Expected Output:
web1should displaywebsite_port=9090(host variable), whileweb2useswebsite_port=8080(group variable).
Lab 1.3: Play and Task Variables
Part A: Using Play Variables
Modify the Playbook:
Update the playbook to include play variables:
Run the Playbook:
Execute the playbook and observe how play variables override group and host variables:
Part B: Using Task Variables
Add Task-Level Variables:
Update the playbook:
Run the Playbook:
Observe how task variables override play variables for the specific task:
Lab 1.4: Extra Vars Precedence
Scenario:
Use extra vars with the -e option to override all other variables.
Steps:
Execute the Playbook with Extra Vars:
Use the following command:
Analyze Results:
Observe how
website_portandwebsite_contentare resolved from extra vars, overriding all other variable sources (inventory, group, host, play, and task variables).
Outcome of Labs:
Participants will understand the variable precedence hierarchy:
Extra vars (
-e) > Task vars > Play vars > Host vars > Group vars > Inventory vars > Default vars.
Participants will explore variable resolution dynamically by modifying or adding variables at different levels and observing their behavior.
This step-by-step progression simplifies understanding variable precedence in Ansible.
Last updated