Ansible role variable is not defined

32 Views Asked by At

I can't user defined variable in ansible role

for example vars/main.yaml

---
hub:
    app_disk: sdb
    size: 40
    vg_name: vg1

And I've tried to refer to that variable in tasks as :

- name: debug variable
  debug:
    var: hub.size

or

    var: hub['size']
    var: "{{ hub.size }}"
    var: "{{ hub['size'] }}"

But every time when I run playbook that include that role it returns that variable is not defined

2

There are 2 best solutions below

0
Vladimir Botka On BEST ANSWER

For example, the below project

shell> tree .
.
├── ansible.cfg
├── hosts
├── pb.yml
└── roles
    └── my_role
        ├── tasks
        │   └── main.yml
        └── vars
            └── main.yml
shell> cat ansible.cfg 
[defaults]
gathering = explicit
inventory = $PWD/hosts
roles_path = $PWD/roles
stdout_callback = yaml
log_path = /var/log/ansible.log

[connection]
pipelining = true
shell> cat hosts
[test]
test_01
test_02
test_03

[test:vars]
ansible_user=admin
ansible_python_interpreter=/usr/local/bin/python3.9
shell> cat pb
- hosts: all
  roles:
    - my_role
shell> cat roles/my_role/tasks/main.yml 
- debug:
    var: hub.size
shell> cat roles/my_role/vars/main.yml 
---
hub:
    app_disk: sdb
    size: 40
    vg_name: vg1

gives as expected

shell> ansible-playbook pb.yml 

PLAY [all] ***********************************************************************************

TASK [my_role : debug] ***********************************************************************
ok: [test_02] => 
  hub.size: '40'
ok: [test_03] => 
  hub.size: '40'
ok: [test_01] => 
  hub.size: '40'

PLAY RECAP ***********************************************************************************
test_01                    : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
test_02                    : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
test_03                    : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
0
sam On

I've found this really depends on how you import the task. If you import the task via the role, then you will have access to the variable in the main.yml task or any other task it imports.

# role_playbook.yml
- name: Import via role
  hosts: all
  roles:
    - example

If you import the task in the playbook, then you don't have the variable in scope.

# task_playbook.yml
- name: Import directly
  hosts: all
  tasks:
    - name: Import task
      ansbile.builtin.import_tasks: roles/example/tasks/main.yml

In this case, I add a vars_files parameter to intentionally load the variables. So it becomes this:

# task_playbook.yml
- name: Import directly
  hosts: all
  vars_files:
    - roles/example/vars/main.yml
  tasks:
    - name: Import task
      ansbile.builtin.import_tasks: roles/example/tasks/main.yml