Ansible 角色变量未定义

问题描述 投票:0回答:1

我无法在 ansible 角色中使用用户定义的变量

例如 vars/main.yaml

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

我尝试在任务中将该变量引用为:

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

or

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

但是每次我运行包含该角色的剧本时,它都会返回该变量未定义

ansible yaml roles
1个回答
0
投票

例如下面的项目

shell> tree .
.
├── ansible.cfg
├── hosts
├── pb.yml
└── roles
    └── my_role
        ├── tasks
        │   └── main.yml
        └── vars
            └── main.yml
cat> 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

符合预期

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
© www.soinside.com 2019 - 2024. All rights reserved.