ansibleyamlroles

Ansible role variable is not defined


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


Solution

  • 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