简体   繁体   中英

Ansible Playbook to get facts from VMWare

Im trying to get the clustername, datastore cluster, port groups, and some other facts from vcenter using ansible. I've read the docs here but the data Im getting in return is almost too much and needs to be filtered. Here's an example of the clustername playbook. It works, but Im looking to get just the name of the cluster. Im outputting it to a yaml file so I can import it into a pipeline later. Here's the code.

- hosts: localhost
  gather_facts: no
  vars_files:
    - vars.yml

  tasks:
    - name: Gather vmware host facts from vCenter
      community.vmware.vmware_cluster_info:
        hostname: '{{ vcenter_hostname }}'
        username: '{{ vcenter_username }}'
        password: '{{ vcenter_password }}'
        datacenter: DC1
        schema: vsphere
        properties:
          - name
      register: clusternames

    - name: Write results to a local file
      copy:
        content: "{{ clusternames.clusters | to_yaml }}"
        dest: "clusternames.yml"

Here are the results:

DC1-QA-DMZ: {name: DC1-QA-DMZ}
DC1-QA-GEN: {name: DC1-QA-GEN}
DC1-QA-SQL: {name: DC1-QA-SQL}

Is there a way to just return this?

name: DC1-QA-DMZ
name: DC1-QA-GEN
name: DC1-QA-SQL

or

DC1-QA-DMZ
DC1-QA-GEN
DC1-QA-SQL

I've played around with set_fact but I cant seem to wrap my head around what I'm missing. I need to do a filter of some sort but Im not familiar with what/how.

You can use the keys method from the dictionary class to return a dictionary view object with the clusters, which you can then convert into a list with the list filter function:

content: "{{ clusternames.clusters.keys() | list | to_yaml }}"

The YAML rendering of this would be:

- DC1-QA-DMZ
- DC1-QA-GEN
- DC1-QA-SQL

as desired in the question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM