在其他游戏中访问变量 - Ansible

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

Ansible版本:2.4.2.0

herehere,我能够在下面写剧本

$ 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----------------

我试过下面的事情

  1. debug: var=hostvars[item]['hostname_output']['stdout']
  2. debug: var=hostvars.item.hostname_output.stdout'

我也尝试过直接主机组,而不是像下面那样迭代item

  1. debug: var=hostvars.all-compute-host.hostname_output.stdout'
  2. debug: var=hostvars['all-compute-host']['hostname_output']['stdout']
ok: [localhost] => {
    "hostvars['all-compute-host']['hostname_output']['stdout']": "VARIABLE IS NOT DEFINED!"
}

我也尝试直接主机名。但没用

  1. debug: var='hostvars.compute01.hostname_output.stdout'
ansible
1个回答
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'] }}"
© www.soinside.com 2019 - 2024. All rights reserved.