Ansible版本:2.4.2.0
$ cat test.yml
- name: Finding Master VMs
hosts: all-compute-host
remote_user: heat-admin
tasks:
- name: Getting master VM's hostname
shell: hostname
register: hostname_output
- name: Access in different play
hosts: localhost
connection: local
tasks:
- name: Testing vars
debug: var='{{ hostvars[item]['hostname_output']['stdout'] }}'
with_items: groups['all-compute-host']
我不想使用gather_facts: true
并从中访问主机名。当我尝试上面的剧本时,低于错误
-----------OUTPUT REMOVED----------------
TASK [Testing vars] *******************************************************************************************************************
fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: u\"hostvars['groups['all-compute-host']']\" is undefined\n\nThe error appears to have been in '/tmp/test.yml': line 18, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n tasks:\n - name: Testing vars\n ^ here\n\nexception type: <class 'ansible.errors.AnsibleUndefinedVariable'>\nexception: u\"hostvars['groups['all-compute-host']']\" is undefined"}
to retry, use: --limit @/tmp/test.retry
-----------OUTPUT REMOVED----------------
我试过下面的事情
debug: var=hostvars[item]['hostname_output']['stdout']
debug: var=hostvars.item.hostname_output.stdout'
我也尝试过直接主机组,而不是像下面那样迭代item
debug: var=hostvars.all-compute-host.hostname_output.stdout'
debug: var=hostvars['all-compute-host']['hostname_output']['stdout']
ok: [localhost] => {
"hostvars['all-compute-host']['hostname_output']['stdout']": "VARIABLE IS NOT DEFINED!"
}
我也尝试直接主机名。但没用
debug: var='hostvars.compute01.hostname_output.stdout'
问题出在你的debug
声明中:
tasks:
- name: Testing vars
debug: var='{{ hostvars[item]['hostname_output']['stdout'] }}'
with_items: groups['all-compute-host']
有两个问题:
var
模块的debug
参数的值在Jinja模板上下文中进行评估。这意味着您不能使用{{...}}
模板标记。with_items
的论点确实需要{{...}}
标记;没有它,你将迭代一个由单个项目组成的列表,文字字符串groups['all-compute-host']
。修复了这两个问题(以及一些小的风格变化),你会得到:
tasks:
- name: Testing vars
debug:
var: hostvars[item].hostname_output.stdout
with_items: "{{ groups['all-compute-host'] }}"