ansible-inventory --list 主机组命令行

ansible-inventory --list host groups command line

我想(仅)从 ansible-inventory 获取主机组名称列表,但是我不得不使用 grep 根据已知的组名称模式在列表中 trim - 例如

ansible-inventory -i inventory/production --list --yaml | grep webserver_.*:$

ansible-playbook my-playbook.yml -i inventory/production --list-hosts

是否有一种从清单中仅提取组名称的简洁方法?

示例hosts.yml:

# NGINX
webserver_1:
  hosts:
    ws1.public.example.com

webserver_2:
  hosts:
    ws2.public.example.com

webserver_2:
  hosts:
    ws2.public.example.com

# EC2 back-ends
backend_ec2_1:
  hosts:
    be1.internal.example.com

backend_ec2_2:
  hosts:
    be2.internal.example.com

backend_ec2_3:
  hosts:
    be3.internal.example.com

[Ansible v2.9.7]

您可以使用 jq 命令解析 ansible-inventory --list 的 json 输出,如下所示:

$ ansible-inventory -i hosts --list | jq .all.children
[
  "backend_ec2_1",
  "backend_ec2_2",
  "backend_ec2_3",
  "ungrouped",
  "webserver_1",
  "webserver_2"
]

或者如果您只想要裸名:

$ ansible-inventory -i hosts --list | jq -r '.all.children[]'
backend_ec2_1
backend_ec2_2
backend_ec2_3
ungrouped
webserver_1
webserver_2