gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 05:11:05 29 4
gpt4 key购买 nike

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. 调试:var=hostvars[item]['hostname_output']['stdout']
  2. 调试:var=hostvars.item.hostname_output.stdout'

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

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

我也试过直接主机名,但是没用

  1. 调试:var='hostvars.compute01.hostname_output.stdout'

最佳答案

问题出在您的 debug 语句上:

tasks:
- name: Testing vars
debug: var='{{ hostvars[item]['hostname_output']['stdout'] }}'
with_items: groups['all-compute-host']

有两个问题:

  • debug 模块的 var 参数的值是在 Jinja 模板上下文中计算的。这意味着您不得使用{{...}} 模板标记。

  • 另一方面,with_items 的参数确实需要{{...}} 标记;否则,您将遍历由单个项目组成的列表,即文字字符串 groups['all-compute-host']

解决了这两个问题(以及一些小的样式更改)后,您将获得:

tasks:
- name: Testing vars
debug:
var: hostvars[item].hostname_output.stdout
with_items: "{{ groups['all-compute-host'] }}"

关于ansible - 在其他游戏中访问变量 - Ansible,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55903007/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com