我在使用变量变量方式从我的剧本访问extra-vars时遇到了问题.
例如,我创建了一个包含内容的group_vars / mygroup.yml文件:
MYVAR=AAAA
然后我调用命令并传递extra-vars:
ansible-playbook -i test playbook.yml –extra-vars“MYVAR = BBB”
我需要从存在变量列表中获取MYVAR的实际值.我试着这样做:
- debug: var=hostvars[inventory_hostname]['MYVAR']
我……
TASK: [test | debug var=AAA] *******************************
ok: [192.168.1.21] => {
"var": {
"AAA": "BBB"
}
}
TASK: [test | debug var=hostvars[inventory_hostname]['AAA']] ***
ok: [192.168.1.21] => {
"var": {
"hostvars[inventory_hostname]['AAA']": "AAA" // ← THIS IS THE PROBLEM
}
}
我怎样才能获得从cli传递的AAA的实际价值?
请不要告诉我直接按名称使用AAA,因为这是更复杂的逻辑的一部分,当我有一个已注册的变量列表,我不能使用他们的名字.
hostvars[inventory_hostname][**item**] ← variable of variable
先感谢您.
更新:或者Ansible已经支持这样的东西了?:
VARNAME: APP_ENV
APP_ENV: blabla
debug: var=${VARNAME} // blabla expected
更新2:github gist有问题解释.
最佳答案 TLDR; – debug:msg =“{{AAA | default(hostvars [inventory_hostname] [‘AAA’])}}”在定义时使用变量AAA,否则使用hostvar(groupvar)AAA
#./main.yml
---
- hosts: all
gather_facts: false
tasks:
- debug: msg="{{ foo }}"
- debug: msg="{{ hostvars[inventory_hostname]['foo'] }}"
- debug: msg="{{ foo|default(hostvars[inventory_hostname]['foo']) }}"
.
#./inventory
[one]
localhost ansible_connection=local
.
#./group_vars/one
---
foo: "bar"
ansible-playbook -i inventory -e“foo = whatever”main.yml
PLAY [all] ********************************************************************
TASK: [debug msg="{{ foo }}"] *************************************************
ok: [localhost] => {
"msg": "whatever"
}
TASK: [debug msg="{{ hostvars[inventory_hostname]['foo'] }}"] *****************
ok: [localhost] => {
"msg": "bar"
}
TASK: [debug msg="{{ foo|default(hostvars[inventory_hostname]['foo']) }}"] ****
ok: [localhost] => {
"msg": "whatever"
}
PLAY RECAP ********************************************************************
localhost : ok=3 changed=0 unreachable=0 failed=0