是否可以使用动态清单为所有主机定义主机变量?
目前,我可以生成一个清单,允许我将变量分配给特定主机,但我想要实现的是这样的:
{
"_meta": {
"hostvars": {
"all": {
"my_global_random_variable": "global_random_value"
}
}
},
"web_servers": {
"children": [],
"hosts": [
"web_server1",
"web_server2"
],
"vars": {}
},
"database_servers": {
"children": [],
"hosts": [
"database_server1"
],
"vars": {}
}
}
这应该允许我从任何上下文访问“my_global_random_variable”,就像我在 vars 文件中定义了该变量一样。
答案1
由 设置的变量dynamic inventory
是inventory variables
。当在多个位置设置变量时,Ansible 会按照以下方式设置值变量优先级:
role defaults [1] inventory vars [2] inventory group_vars inventory host_vars playbook group_vars playbook host_vars host facts play vars play vars_prompt play vars_files registered vars set_facts role and include vars block vars (only for tasks in block) task vars (only for the task) extra vars (always win precedence)
库存中设置的变量优先级相对较低。因此无需使用dynamic inventory
它来实现这一点。只需在角色级别设置变量即可。
答案2
我最终使用查找插件而不是库存来检索我的变量。
有关查找的更多信息:https://docs.ansible.com/ansible/playbooks_lookups.html
答案3
我想这样做,并且似乎可以采用以下方法(针对您的示例进行了调整):
{
"all": {
"vars": {
"my_global_random_variable": "global_random_value"
}
},
"web_servers": {
"children": [],
"hosts": [
"web_server1",
"web_server2"
],
"vars": {}
},
"database_servers": {
"children": [],
"hosts": [
"database_server1"
],
"vars": {}
}
}
可能不是最佳实践,但可以保持事情简单。