Junior
Name the ways to assign variables in Ansible.
sobes.tech AI
Answer from AI
Variables in Ansible can be set in several ways:
- Inventory files: in
hostsfiles or separate files in thegroup_varsandhost_varsdirectories. - Command line: using the
--extra-varsor-eflag. - Playbooks: in the
vars,vars_files,include_varssections. - Roles: in the
varsdirectories or through parameters when calling a role. - Ansible configuration files: in
ansible.cfg, but this is not recommended for specific values. - Dynamic Inventory: through scripts that generate inventory and variables on the fly.
- Vaults: for storing secret data.
The priority of variable assignment in Ansible from low to high:
ansible.cfg- Inventory files (
host_vars,group_vars) - Roles (from default, then from vars)
- The
varssection in the playbook - Variables passed through the command line
Example of setting a variable in inventory:
# inventory.ini
[webservers]
web1 ansible_host=192.168.1.100
[webservers:vars]
http_port=80
Example of setting a variable in a playbook:
# playbook.yml
---
- name: Configure webserver
hosts: webservers
vars:
greeting: "Hello, World!"
tasks:
- name: Print greeting
debug:
msg: "{{ greeting }}"
Example of setting a variable via command line:
ansible-playbook playbook.yml -e "user=admin"