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

use*_*765 2 ansible ansible-inventory

我想(仅)从 ansible-inventory 获取主机组名称列表,但是我必须使用 grep 根据已知的组名称模式来修剪列表 - 例如

  • 干净的输出,但混乱的命令行,需要提前知道组名称模式:

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
Run Code Online (Sandbox Code Playgroud)

[Ansible v2.9.7]

lar*_*sks 5

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

$ ansible-inventory -i hosts --list | jq .all.children
[
  "backend_ec2_1",
  "backend_ec2_2",
  "backend_ec2_3",
  "ungrouped",
  "webserver_1",
  "webserver_2"
]
Run Code Online (Sandbox Code Playgroud)

或者如果你只想要简单的名字:

$ ansible-inventory -i hosts --list | jq -r '.all.children[]'
backend_ec2_1
backend_ec2_2
backend_ec2_3
ungrouped
webserver_1
webserver_2
Run Code Online (Sandbox Code Playgroud)