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'
答案 0 :(得分:0)
问题出在您的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'] }}"