Ansible - 将库存主机和变量读取到 group_vars/all 文件 [英] Ansible - read inventory hosts and variables to group_vars/all file

查看:40
本文介绍了Ansible - 将库存主机和变量读取到 group_vars/all 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个虚拟的疑问,让我卡住了很长时间.我有一个非常平庸的清单文件,其中包含主机和变量:

I have a dummy doubt that keeps me stuck for a long time. I have a very banal inventory file with hosts and variables:

[lb]
10.112.84.122

[tomcat]
10.112.84.124

[jboss5]
10.112.84.122

...

[tests:children]
lb
tomcat
jboss5

[default:children]
tests

[tests:vars]
data_base_user=NETWIN-4.3
data_base_password=NETWIN
data_base_encrypted_password=
data_base_host=10.112.69.48
data_base_port=1521
data_base_service=ssdenwdb
data_base_url=jdbc:oracle:thin:@10.112.69.48:1521/ssdenwdb

问题是我需要从 group_vars/all 文件访问清单文件中的所有这些主机和变量.

The problem is that I need to access all these hosts and variables, in the inventory file, from the group_vars/all file.

我尝试了以下方式访问主机IP:

I've tried the following manners to access the host IP:

{{ lb }}
"{{ hostvars[lb] }}"
"{{ hostvars['lb'] }}"
{{ hostvars[lb] }}

要访问我尝试过的主变量:

To access a host variable I tried:

"{{ hostvars[tests].['data_base_host'] }}"

他们都错了!!!谁能帮我找出访问主机和变量的最佳实践,不是从剧本而是从变量文件?

All of them are wrong!!! Can anyone help me find out the best practice to access hosts and variables, not from a playbook but from a variables file?

好的.让我们澄清一下.

Ok. Let's clarify.

问题: 在变量文件中使用清单文件中声明的主机,比方说:group_vars/all.

Problem: Use a host declared in the inventory file in a variable file, let's say: group_vars/all.

示例:我有一个带有 IP:10.112.83.37 的数据库主机.

Example: I have a DB host with IP:10.112.83.37.

库存文件:

[db]
10.112.83.37

在 group:vars/all 文件中,我想使用该 IP 来构建变量.

In the group:vars/all file I want to use that IP to build a variable.

group_vars/所有文件:

group_vars/all file:

data_base_url=jdbc:oracle:thin:@{{ db }}:1521/ssdenwdb

在模板中,我使用 group_vars/all 文件中内置的变量.

In a template I use the variable built in the group_vars/all file.

模板文件:

oracle_url = {{ data_base_url }}

问题在于 group_vars/all 文件中的 {{ db }} 变量没有被 DB 主机 IP 替换.用户只能编辑库存文件.

The problem is that the {{ db }} variable in the group_vars/all file is not replaced by the DB host IP. The user can only edit the inventory file.

推荐答案

- name: host
   debug: msg="{{ item }}" 
   with_items:
    - "{{ groups['tests'] }}"

这段代码将给出信息:

'10.112.84.122'
'10.112.84.124'

as groups['tests'] 基本上返回唯一 ip 地址列表 ['10.112.84.122','10.112.84.124']groups['tomcat'][0] 返回 10.112.84.124.

as groups['tests'] basically return a list of unique ip addresses ['10.112.84.122','10.112.84.124'] whereas groups['tomcat'][0] returns 10.112.84.124.

这篇关于Ansible - 将库存主机和变量读取到 group_vars/all 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆