Menu

Virtual Geek

Tales from real IT system administrators world and non-production environment

Developing and writing custom Ansible Python module Part 2

This is a second part of Developing and writing Ansible Python custom module for VMware pyvmomi example. In this example I have extended writing python module for VMware ansible to get more information from vCenter server from one single python ansible module script. 

Download this custom ansible module for vCenter example here or it is also available github.com.

In this module it can get information regarding ESXi servers, VMs and it gets the list and configures SCSI adapter on VMs. Below is one of the module example to get inventory Virtual Machines list from vCenter Server.

#!/usr/bin/env python3

DOCUMENTATION = '''
---
module: custom_vm_info
short_description: Retrieve information about virtual machines from vCenter inventory
'''

from ansible.module_utils.basic import AnsibleModule
from pyVim.connect import SmartConnect, Disconnect
from pyVmomi import vim
import ssl

def main():
    module = AnsibleModule(
        argument_spec=dict(
            vcenter_host=dict(type='str', required=True),
            vcenter_user=dict(type='str', required=True),
            vcenter_password=dict(type='str', required=True, no_log=True),
            vm_name=dict(type='str', default=None)
        )
    )
    
    vcenter_host = module.params['vcenter_host']
    vcenter_user = module.params['vcenter_user']
    vcenter_password = module.params['vcenter_password']
    vm_name = module.params['vm_name']
    
    s = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
    s.verify_mode = ssl.CERT_NONE
    
    try:
        si = SmartConnect(host=vcenter_host, user=vcenter_user, pwd=vcenter_password, sslContext=s)
        content = si.content
        
        if vm_name is None:
            vms = get_all_objs(content, [vim.VirtualMachine])
            vm_list = []
            for vm in vms:
                vm_info = get_vm_info(vm)
                vm_list.append(vm_info)
            Disconnect(si)
            response = {'virtual_machines': vm_list}
            module.exit_json(changed=False, meta=response)
        else:
            vm = get_vm_by_name(content, vm_name)
            if vm:
                vm_info = get_vm_info(vm)
                Disconnect(si)
                module.exit_json(changed=False, meta=vm_info)
            else:
                Disconnect(si)
                module.fail_json(msg=f"Virtual machine '{vm_name}' not found.")
    except Exception as e:
        module.fail_json(msg=str(e))

def get_all_objs(content, vimtype):
    obj = {}
    container = content.viewManager.CreateContainerView(content.rootFolder, vimtype, True)
    for managed_object_ref in container.view:
        obj.update({managed_object_ref: managed_object_ref.name})
    return obj

def get_vm_by_name(content, vm_name):
    container = content.viewManager.CreateContainerView(content.rootFolder, [vim.VirtualMachine], True)
    for vm in container.view:
        if vm.name == vm_name:
            return vm
    return None

def get_vm_info(vm):
    return {
        'id': vm._moId,
        'name': vm.name,
        'power_state': vm.runtime.powerState,
        'connection_state': vm.runtime.connectionState,
        'guest_fullname': vm.config.guestFullName,
        'num_cpus': vm.config.hardware.numCPU,
        'memory_size_mb': vm.config.hardware.memoryMB,
        'esxi_host': get_vm_esxi_host(vm),
        'cluster': get_vm_cluster(vm),
        'datastore': get_vm_datastore(vm),
        'folder': get_vm_folder(vm),
        'ip_addresses': get_vm_ip_addresses(vm)
    }

def get_vm_esxi_host(vm):
    if vm.runtime.host:
        return vm.runtime.host.name
    return None

def get_vm_cluster(vm):
    if vm.resourcePool:
        return vm.resourcePool.owner.name
    return None

def get_vm_datastore(vm):
    if vm.datastore:
        return vm.datastore[0].name
    return None

def get_vm_folder(vm):
    if vm.parent:
        return vm.parent.name
    return None

def get_vm_ip_addresses(vm):
    ip_addresses = []
    if vm.guest and vm.guest.net:
        for net in vm.guest.net:
            if net.ipAddress:
                ip_addresses.extend(net.ipAddress)
    return ip_addresses

if __name__ == "__main__":
    main()

VMware ansible get information list scsiadapter set scsiadapter information pyvmomi python py custom module information.png

Useful Articles
Getting started Ansible AWX tower for IT automation run first playbook
Ansible for VMwary Using vmware_vm_inventory dynamic inventory plugin
Ansible selectattr The error was TemplateRuntimeError no test named 'equalto'
ansible create an array with set_fact
Ansible get information from esxi advanced settings nested dictionary with unique keynames
Install Ansible AWX Tower on Ubuntu Linux
Ansible AWX installation error Cannot have both the docker-py and docker python modules
Ansible AWX installation error docker-compose run --rm --service-ports task awx-manage migrate --no-input
docker: Got permission denied while trying to connect to the Docker daemon socket
Ansible AWX Tower create Manual SCM (Source Control Credential Type) project
Reset Ansible AWX Tower admin password
Install Ansible AWX on Microsoft Windows OS
Step by Step Install Ansible on Ubuntu OS
Install Ansible AWX Tower on Ubuntu Linux OS
Ansible AWX Tower Github inventory integration | Github inventory source

Go Back

Comment

Blog Search

Page Views

11496740

Follow me on Blogarama