从Ansible Output中筛选出数据



我需要从运行剧本的输出中提取主机名,如下所示。

ok: [localhost] =>
msg:
changed: false
clusters:
RDG1-DC-2:
datacenter: RDG1
drs_default_vm_behavior: fullyAutomated
drs_enable_vm_behavior_overrides: true
drs_vmotion_rate: 3
enable_ha: false
enabled_drs: true
enabled_vsan: false
ha_admission_control_enabled: true
ha_failover_level: 1
ha_host_monitoring: enabled
ha_restart_priority:
- medium
ha_vm_failure_interval:
- 30
ha_vm_max_failure_window:
- -1
ha_vm_max_failures:
- 3
ha_vm_min_up_time:
- 120
ha_vm_monitoring: vmMonitoringDisabled
ha_vm_tools_monitoring:
- vmMonitoringDisabled
hosts:
- folder: /RDG1/host/RDG1-DC-2
name: esxi7-host3.hmlab.local
- folder: /RDG1/host/RDG1-DC-2
name: esxi7-host4.hmlab.local
moid: domain-c1009
resource_summary:
cpuCapacityMHz: 27264
cpuUsedMHz: 494
memCapacityMB: 14326
memUsedMB: 6493
pMemAvailableMB: 0
pMemCapacityMB: 0
storageCapacityMB: 50944
storageUsedMB: 37489
tags: []
vsan_auto_claim_storage: false
failed: false

这个输出所需要的只是从主机中提取名称:item

它应该给我:

  • esxi7-host3.hmlab.local
  • esxi7-host4.hmlab.local

我确实尝试过使用以下内容,但它将其作为dict吐出,而不是作为我可以循环的列表

- set_fact:
host_clusters: "{{ item.value.hosts | json_query('[*].name') | to_nice_yaml }}"
with_dict: "{{ cluster_info.clusters }}"
loop_control:
label: '{{ item.key }}'
- debug:
msg: "{{ host_clusters }}"

在不使用循环的情况下,无论是JMESPath查询,都可以更容易地使用Python字典的values方法和map过滤器。

- debug:
var: (cluster_info.clusters.values() | first).hosts | map(attribute='name')

如果你有多个集群:

- debug:
var: cluster_info.clusters.values() | map(attribute='hosts') | flatten | map(attribute='name')

给定剧本:

- hosts: localhost
gather_facts: no
tasks:
- debug:
var: (cluster_info.clusters.values() | first).hosts | map(attribute='name')
vars:
cluster_info:
clusters:
RDG1-DC-2:
hosts:
- folder: /RDG1/host/RDG1-DC-2
name: esxi7-host3.hmlab.local
- folder: /RDG1/host/RDG1-DC-2
name: esxi7-host4.hmlab.local

这产生:

TASK [debug] *********************************************************************
ok: [localhost] => 
(cluster_info.clusters.values() | first).hosts | map(attribute='name'):
- esxi7-host3.hmlab.local
- esxi7-host4.hmlab.local

相关内容

  • 没有找到相关文章