Ansible-将清单主机和变量读取到group_vars/所有文件 [英] Ansible - read inventory hosts and variables to group_vars/all file
问题描述
我有一个很奇怪的疑问,使我长期困扰.我有一个非常普通的清单文件,其中包含主机和变量:
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] }}
我尝试访问主机变量:
"{{ 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 }}
变量没有被数据库主机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'
如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/所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!