引用 Ansible Inventory 层次结构

Referencing Ansible Inventory Hierarchy

我希望能够将 ansible 主机的直接父级引用为变量。

举以下例子盘点:

[resourcegroup1]
host1
host2

[resourcegroup2]
host3
host4

[application:children]
[resourcegroup1]

[database:children]
[resourcegroup2]

[environoments:children]
[application]
[database]

[enivronoments]
dev
staging
prod

我想 运行 一个可以引用主机父级的播放循环任务。示例:

tasks:
- name: Start Datanbase Servers
  with_items: "{{ groups['database'] }}"   
  azure_rm_virtualmachine:
    name: "{{ item }}"
    resource_group: "{{ item.parent }}"
    started: yes
    allocated: yes

{{ item }} 会遍历 "host3" 和 "host4" 的值,而我正在寻找可以代替 {{ item.parent }} 的值是主机的直接父级,在这种情况下:"resourcegroup2".

有什么方法可以引用库存的层次结构吗?

经过一些快速研究后,Ansible 似乎没有内置那种功能。

根据在 Ansible Github 回购中打开的门票,听起来人们对此功能很感兴趣,但从未开发过。可能是因为有用性和复杂性之间的斗争。

Ansible Tix

Ansible Tix

以下是上述链接的一些片段:

It would be nice to have a way of recreating inventory group hierarchy inside i.e. Jinja2 template.

@kinvaris We have dynamic inventories for this. You could just write a small dynamic inventory script, and have it translate. I don't see why this is a necessary addition, it only complicates the tools even more.

如果您只想要与主机关联的组列表,而不关心层次结构:

'{{hostvars["host1"]}}'

您将得到如下列表:

"groups": {
            "all": [
                "host"
            ],
            "child": [
                "host1"
            ],
            "parent": [
                "host1"
            ],
            "ungrouped": []
        },