ansible - Ansible:从库存文件中获取变量值
问题描述
我在从库存文件中获取ansible_user
under的值时遇到问题。rhel
以下是我尝试获取的几种方法,每次都显示 undefined rhel
。关于如何检索它的任何建议?
- set_fact:
SSHUSER: "{{ hostvars.[rhel].ansible_user }}"
- set_fact:
SSHUSER: "{{ rhel.ansible_user }}"
---
all:
vars:
project: test
hosts:
children:
test_vm:
hosts: 10.10.10.4
example_vm:
hosts: 10.10.10.5
ubuntu:
children:
test_vm:
vars:
os: ubuntu
ansible_user: "testuser"
rhel:
children:
example_vm:
vars:
os: rhel
ansible_user: "exampleuser"
解决方案
rhel
您引用的是一个组,而不是一个主机——一个主机可能属于多个组。为了实现“组 rhel 的某些成员的主机变量”,您想要的表达式是 jinja2 表达式:{{ hostvars[groups["rhel"][0]].ansible_user }}
ansible 清单主机名的字符串列表在哪里groups["rhel"]
,如果有人假设它们都有一个等价物ansible_user
,那么抓住第一个应该是安全的,它是groups["rhel"][0]
或者更冗长但可能更清晰groups["rhel"]|first
然后,我们想要那个主机hostvars
,而不是我们自己的;因为它是由 ansible 库存主机名索引的,我们可以将该值插入到字典中,因为它是每个主机变量,然后返回您请求的事实hostvars
dict[str, dict]
hostvars
hostvars[groups["rhel"][0]]
hostvars[groups["rhel"][0]].ansible_user
ansible_user
推荐阅读
- java - 在 NetBeans 12.0 中,我收到错误无法访问 java.lang
- node.js - 通过 id 属性使用 gridfs 存储桶从文件集合中检索文档时遇到问题
- python - 使用 Python 嗅探协议
- java - 如何在 Maven 发布插件中使用“projectVersionPolicyId”?
- go - Golang for 似乎跳过了一些实体
- python - Python:ndarray 的 nanargmax 版本
- python - 如何分配具有空值或空值的字典
- typescript - 使用 GOT 发起 API 请求时量角器脚本失败
- javascript - 如果出现 404 错误,在 XMLHttpRequest 中只刷新一次页面
- math - 大量数的模