Assigning Variables to Groups
Ansible allows you to assign variables to groups in the inventory file. These variables can be used in playbooks and templates, making your Ansible code more flexible and reusable.
Edit the inventory
file:
nano /home/labex/project/inventory
Update the content to:
[webservers]
localhost ansible_connection=local
[production:children]
webservers
[webservers:vars]
http_port=80
This assigns the variable http_port
with a value of 80 to all hosts in the webservers
group. The :vars
suffix is used to define variables for a group.
Save and exit the editor.
Now, let's create a simple playbook to display this variable. A playbook is a YAML file that defines a set of tasks to be executed on hosts. Create a new file named show_http_port.yml
:
nano /home/labex/project/show_http_port.yml
Add the following content:
---
- name: Show HTTP Port
hosts: webservers
tasks:
- name: Display HTTP Port
debug:
msg: "The HTTP port is {{ http_port }}"
This playbook:
- Targets the
webservers
group
- Has a single task that uses the
debug
module to display a message
- Uses the
{{ http_port }}
syntax to reference the variable we defined in the inventory
Save and exit the editor.
Run the playbook:
ansible-playbook -i inventory show_http_port.yml
You should see output displaying the HTTP port value:
PLAY [Show HTTP Port] ********************************************************
TASK [Gathering Facts] ********************************************************
ok: [localhost]
TASK [Display HTTP Port] ******************************************************
ok: [localhost] => {
"msg": "The HTTP port is 80"
}
PLAY RECAP ********************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
This demonstrates that the variable we defined in the inventory is accessible in our playbook.