Sobes.tech
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 hosts files or separate files in the group_vars and host_vars directories.
  • Command line: using the --extra-vars or -e flag.
  • Playbooks: in the vars, vars_files, include_vars sections.
  • Roles: in the vars directories 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:

  1. ansible.cfg
  2. Inventory files (host_vars, group_vars)
  3. Roles (from default, then from vars)
  4. The vars section in the playbook
  5. 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"