コード例 #1
0
ファイル: vcloud.py プロジェクト: xlab-si/wrapanapi
    def count_vcloud(self, client):
        """
        Obtain counts via vCloud API. Multiple dependent requests are needed therefore
        we collect them all in one pass to avoid repeating previous requests e.g. to
        fetch VMs, one must first fetch vApps and vdcs.
        :param client:
        :return:
        """
        org_resource = client.get_org()
        org = Org(client, resource=org_resource)

        stats = {
            'num_availability_zone': 0,
            'num_orchestration_stack': 0,
            'num_vm': 0
        }

        for vdc_info in org.list_vdcs():
            stats['num_availability_zone'] += 1
            vdc = VDC(client, resource=org.get_vdc(vdc_info['name']))
            for vapp_info in vdc.list_resources():
                try:
                    vapp_resource = vdc.get_vapp(vapp_info.get('name'))
                except Exception:
                    continue  # not a vapp (probably vapp template or something)

                vapp = VApp(client, resource=vapp_resource)
                stats['num_orchestration_stack'] += 1
                stats['num_vm'] += len(vapp.get_all_vms())

        return stats
コード例 #2
0
def GetvAppObj(parameters, client, virtual_machine):
    """
  Get vApp Object
  """
    try:

        # Get the org object that corresponds with the org provided at runtime
        org_resource = client.get_org()
        org = Org(client, resource=org_resource)

        #  Get the VDC object that correspondes with the VDC provided at runtime
        vdc_resource = org.get_vdc(parameters['VCD_VDC'])
        vdc = VDC(client, resource=vdc_resource)

        # Loop through all vApps until matching virtual machine is found, return vapp
        vapps = vdc.list_resources(EntityType.VAPP)
        for vapp in vapps:
            vapp_name = vapp.get('name')
            vapp_resource = vdc.get_vapp(vapp_name)
            vapp = VApp(client, resource=vapp_resource)

            for vm in vapp.get_all_vms():
                if vm.get('name') == virtual_machine:
                    return vapp

    except Exception as e:
        print("ERROR: Failed To Get vApp Object For Virtual Machine: '" +
              virtual_machine + "'")
        print(e)
        exit(1)
コード例 #3
0
ファイル: awx-vcloud-inv.py プロジェクト: armahan/Scripts
def get_all_host(host, org, user, password, vdc):

    #Linux guest hosts
    linux_os_list = ['CentOS 7 (64-bit)', 'Ubuntu Linux (64-bit)', 'CentOS 8 (64-bit)']

    #Windows guest hosts
    win_os_list = ['Microsoft Windows Server 2016 or later (64-bit)', 'Microsoft Windows Server 2019 (64-bit)']

    #Host list of all Vapps
    host_list = {}


    client = Client(host,
                verify_ssl_certs=True,#SSL 
                log_requests=False,
                log_headers=False,
                log_bodies=False)
    client.set_highest_supported_version()
    client.set_credentials(BasicLoginCredentials(user, org, password))

    org_resource = client.get_org()
    org = Org(client, resource=org_resource)

    vdc_resource = org.get_vdc(vdc)
    vdc = VDC(client, resource=vdc_resource)

    vapps = vdc.list_resources()

    win_list = []
    linux_list = []
    other_os_list = []
    hostvars = {}
    for vapp in vapps:
        if vapp["type"] == "application/vnd.vmware.vcloud.vApp+xml":
            currentHref = vdc.get_vapp_href(vapp["name"])
            currentVapp = VApp(client, href=currentHref)
            for vm in currentVapp.get_all_vms():
                vmName = vm.get('name')
                vmOs = VM(client, resource=vm)
                vOs = vmOs.get_operating_system_section()
                try:
                    vmIp = currentVapp.get_primary_ip(vmName)
                except:
                    pass
                if vmOs.is_powered_on():
                    if vOs.Description in win_os_list:
                        win_list.append(vmName)
                        hostvars.update({vmName:{'ansible_host':vmIp}})
                    elif vOs.Description in linux_os_list:
                        linux_list.append(vmName)
                        hostvars.update({vmName:{'ansible_host':vmIp}})
                    else:
                        other_os_list.append(vmName)
                        hostvars.update({vmName:{'ansible_host':vmIp}})
                    host_list.update({'windows':{'hosts':win_list}})
                    host_list.update({'linux':{'hosts':linux_list}})
                    host_list.update({'others':{'hosts':other_os_list}})
                    host_list.update({'_meta':{'hostvars':hostvars}})
    return host_list
コード例 #4
0
def main():
    argument_spec = vcd_fetch_vapps_argument_spec()
    response = dict(msg=dict(type='str'), vapps=[])
    module = VcdAnsibleModule(argument_spec=argument_spec,
                              supports_check_mode=True)

    try:
        vdc = module.params['vdc']
        client = module.client
        org_resource = client.get_org()
        org = Org(client, resource=org_resource)
        vdc_resource = org.get_vdc(vdc)
        vdc = VDC(client, resource=vdc_resource)
        vapps = vdc.list_resources(EntityType.VAPP)

        for vapp in vapps:
            response['vapps'].append(vapp.get('name'))

    except Exception as error:
        response['msg'] = error.__str__()
        module.fail_json(**response)

    module.exit_json(**response)
コード例 #5
0
ファイル: list-vapps.py プロジェクト: westsouthnight/pyvcloud
# Disable warnings from self-signed certificates.
requests.packages.urllib3.disable_warnings()

# Login. SSL certificate verification is turned off to allow self-signed
# certificates.  You should only do this in trusted environments.
print("Logging in: host={0}, org={1}, user={2}".format(host, org, user))
client = Client(host,
                api_version='29.0',
                verify_ssl_certs=False,
                log_file='pyvcloud.log',
                log_requests=True,
                log_headers=True,
                log_bodies=True)
client.set_credentials(BasicLoginCredentials(user, org, password))

print("Fetching Org...")
org_resource = client.get_org()
org = Org(client, resource=org_resource)

print("Fetching VDC...")
vdc_resource = org.get_vdc(vdc)
vdc = VDC(client, resource=vdc_resource)
print("Fetching vApps....")
vapps = vdc.list_resources(EntityType.VAPP)
for vapp in vapps:
    print(vapp.get('name'))

# Log out.
print("Logging out")
client.logout()
コード例 #6
0
        # Retrieve VDC Org Networks ---------------------------------------------------------------
        cprint("\nList of VDC Org Networks from VDC {}".format(vdc['name']),
               'yellow')
        orgnets = vdc_instance.list_orgvdc_network_resources()
        orgnettable = PrettyTable(
            ["Organization", "VDC name", "Org Nw name", "Org Nw href"])
        for k in range(len(orgnets)):
            orgnettable.add_row([
                o.get('name'), vdc['name'], orgnets[k].attrib['name'],
                orgnets[k].attrib['href']
            ])
        print(orgnettable)

        # Retrieve all vApps from vCD -------------------------------------------------------------
        vapps_list = vdc_instance.list_resources()
        for vapp in vapps_list:
            # Exclude VM Templates from Catalogs
            # There're two types vApp+xml or vAppTemplate+xml
            if vapp.get('type').split('.')[-1] == 'vApp+xml':
                # print("\nFetching vAPP {}".format(vapp['name']))
                vapp_resource = vdc_instance.get_vapp(vapp['name'])
                vapp_instance = VApp(client, resource=vapp_resource)

                vapptable = PrettyTable([
                    "VAPP name", "VM name", "VM href", "Connection", "MAC",
                    "IP", "Primary"
                ])

                'application/vnd.vmware.vcloud.vAppTemplate+xml'
コード例 #7
0
ファイル: list-vdc-resources.py プロジェクト: vmware/pyvcloud
user = sys.argv[3]
password = sys.argv[4]

# Disable warnings from self-signed certificates.
requests.packages.urllib3.disable_warnings()

# Login. SSL certificate verification is turned off to allow self-signed
# certificates.  You should only do this in trusted environments.
print("Logging in: host={0}, org={1}, user={2}".format(host, org, user))
client = Client(host, verify_ssl_certs=False)
client.set_highest_supported_version()
client.set_credentials(BasicLoginCredentials(user, org, password))

print("Fetching Org...")
org = Org(client, resource=client.get_org())
print("Fetching VDCs...")
for vdc_info in org.list_vdcs():
    name = vdc_info['name']
    href = vdc_info['href']
    print("VDC name: {0}\n    href: {1}".format(
        vdc_info['name'], vdc_info['href']))
    vdc = VDC(client, resource=org.get_vdc(vdc_info['name']))
    print("{0}{1}".format("Name".ljust(40), "Type"))
    print("{0}{1}".format("----".ljust(40), "----"))
    for resource in vdc.list_resources():
        print('%s%s' % (resource['name'].ljust(40), resource['type']))

# Log out.
print("Logging out")
client.logout()
コード例 #8
0
# Disable warnings from self-signed certificates.
requests.packages.urllib3.disable_warnings()

# Login. SSL certificate verification is turned off to allow self-signed
# certificates.  You should only do this in trusted environments.
print("Logging in: host={0}, org={1}, user={2}".format(host, org, user))
client = Client(host,
                api_version='29.0',
                verify_ssl_certs=False,
                log_file='pyvcloud.log',
                log_requests=True,
                log_headers=True,
                log_bodies=True)
client.set_credentials(BasicLoginCredentials(user, org, password))

print("Fetching Org...")
org_resource = client.get_org()
org = Org(client, resource=org_resource)

print("Fetching VDC...")
vdc_resource = org.get_vdc(vdc)
vdc = VDC(client, resource=vdc_resource)
print("Fetching vApps....")
vapps = vdc.list_resources()
for vapp in vapps:
    print(vapp.get('name'))

# Log out.
print("Logging out")
client.logout()
class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
    NAME = 'zarrenspry.vcloud_director.vcloud_director_inventory'

    def __init__(self):

        super().__init__()
        self.client = None
        self.vdc = None
        self.org = None
        self.group_keys = []
        self.machines = []
        self.inventory = None
        self.vapp_resource = None
        self.root_group = None

        self.cache_needs_update = False
        self.cache_key = None

    def _authenticate(self):
        _password = self.templar.template(self.get_option('password'))
        if not _password:
            raise AnsibleError(f"Password returned None. Check and try again.")

        try:
            self.client = Client(
                self.get_option('host'),
                api_version=self.get_option('api_version'),
                verify_ssl_certs=self.get_option('verify_ssl_certs'),
                log_file=None)
            self.client.set_credentials(
                BasicLoginCredentials(self.get_option('user'),
                                      self.get_option('org'), _password))
        except Exception as e:
            raise AnsibleError(f"Failed to login to endpoint. MSG: {e}")

    def _get_org(self):
        try:
            self.org = Org(self.client, resource=self.client.get_org())
        except Exception as e:
            raise AnsibleError(f"Failed to create Org object. MSG: {e}")

    def _get_vdc(self):
        self._authenticate()
        self._get_org()
        try:
            self.vdc = VDC(self.client,
                           resource=self.org.get_vdc(
                               self.get_option('target_vdc')))
        except Exception as e:
            raise AnsibleError(f"Failed to create VDC object. MSG: {e}")

    def _get_vapps(self):
        self._get_vdc()
        try:
            return self.vdc.list_resources(EntityType.VAPP)
        except Exception as e:
            raise AnsibleError(f"Failed to get all vapp resources, MSG:: {e}")

    def _get_vapp_resource(self, name):
        try:
            return VApp(self.client, resource=self.vdc.get_vapp(name))
        except Exception as e:
            raise AnsibleError(f"Failed to get vApp resource, MSG: {e}")

    def _get_vm_resource(self, vm):
        try:
            return VM(self.client, resource=self.vapp_resource.get_vm(vm))
        except Exception as e:
            raise AnsibleError(f"Failed to get vm resource, MSG: {e}")

    def _add_host(self, machine):
        name, ip = machine.get('name'), machine.get('ip')
        self.display.vvvv(f"Adding {name}:{ip} to inventory.")
        self.inventory.add_host(name, self.root_group)
        self.inventory.set_variable(name, 'ansible_host', ip)
        for meta in machine.keys():
            if meta not in ["metadata", "name", "ip"]:
                self.inventory.set_variable(name, meta, machine.get(meta))

    def _add_group(self, machine, group_keys):
        for key in group_keys:
            if key in machine.get('metadata').keys():
                data = machine.get('metadata').get(key)
                # Is this composite data ?
                if re.match('\[["\']\w+["\'],.*\]', data):
                    self.display.vvvv(f"Composite data found within {key}")
                    for group in re.findall('[a-zA-Z_]+', data):
                        if group != self.root_group and re.match(
                                '[\w_]', group):
                            self.display.vvvv(
                                f"Adding {machine.get('name')}:{machine.get('ip')} to group {group}"
                            )
                            self.inventory.add_group(group)
                            self.inventory.add_child(
                                group,
                                machine.get('name').lower())
                else:
                    if data != self.root_group:
                        self.display.vvvv(
                            f"Adding {machine.get('name')}:{machine.get('ip')} to group {data}"
                        )
                        self.inventory.add_group(data)
                        self.inventory.add_child(data,
                                                 machine.get('name').lower())

    def _query(self, vm):
        vm_name = str(vm.get('name')).lower().replace("-",
                                                      "_").replace(".", "")
        vm_ip = None
        metadata = {}

        for network in vm.NetworkConnectionSection:
            for connection in network.NetworkConnection:
                if connection.IpAddress in [
                        str(i)
                        for i in list(IPNetwork(self.get_option('cidr')))
                ]:
                    vm_ip = str(connection.IpAddress)

        vm_resource = self._get_vm_resource(vm.get('name'))
        for meta in vm_resource.get_metadata():
            if hasattr(meta, "MetadataEntry"):
                metadata = {
                    i.Key.pyval: i.TypedValue.Value.pyval
                    for i in meta.MetadataEntry
                }

        if vm_ip:
            self.machines.append({
                'name':
                vm_name,
                'ip':
                vm_ip,
                'metadata':
                metadata,
                'os_type':
                str(vm.VmSpecSection[0].OsType),
                'power_state':
                VCLOUD_STATUS_MAP[int(vm.get('status'))],
                'hardware_version':
                str(vm.VmSpecSection[0].HardwareVersion),
                'vmware_tools_version':
                str(vm.VmSpecSection[0].VmToolsVersion),
                'virtual_machine_id':
                str(vm.GuestCustomizationSection[0].VirtualMachineId),
                'memory_hot_enabled':
                str(vm.VmCapabilities[0].MemoryHotAddEnabled),
                'cpu_hot_enabled':
                str(vm.VmCapabilities[0].CpuHotAddEnabled),
                'storage_profile':
                str(vm.StorageProfile.get("name"))
            })

    def _populate(self, machine):
        group_keys = self.get_option('group_keys')
        filters = self.get_option('filters')
        if filters:
            for _ in machine.get('metadata').items() & filters.items():
                self._add_host(machine)
                if group_keys:
                    self._add_group(machine, group_keys)
        else:
            self._add_host(machine)
            if group_keys:
                self._add_group(machine, group_keys)

    def _config_cache(self, cache):
        self.load_cache_plugin()
        if cache:
            try:
                self.machines = self._cache[self.cache_key]
            except KeyError:
                self.cache_needs_update = True

    def verify_file(self, path):
        valid = False
        if super().verify_file(path):
            if path.endswith(('vcloud.yaml', 'vcloud.yml')):
                valid = True
        return valid

    def parse(self, inventory, loader, path, cache=True):

        super().parse(inventory, loader, path)

        self._read_config_data(path)

        self.templar = Templar(loader=loader)
        self.inventory = inventory
        self.root_group = self.get_option('root_group')

        self.inventory.add_group(self.root_group)
        self.cache_key = self.get_cache_key(path)

        cache = self.get_option('set_cache')
        self._config_cache(cache)

        if not cache or self.cache_needs_update:
            for vapp in self._get_vapps():
                self.vapp_resource = self._get_vapp_resource(vapp.get('name'))
                vms = self.vapp_resource.get_all_vms()
                for vm in vms:
                    self._query(vm)
            try:
                self._cache[self.cache_key] = self.machines
            except Exception as e:
                raise AnsibleError(f"Failed to populate data: {e}")
        for machine in self.machines:
            self._populate(machine)
コード例 #10
0
#!/usr/bin/env python3

import os
from pyvcloud.vcd.client import BasicLoginCredentials
from pyvcloud.vcd.client import Client
from pyvcloud.vcd.client import EntityType
from pyvcloud.vcd.org import Org
from pyvcloud.vcd.vdc import VDC
import requests

requests.packages.urllib3.disable_warnings()

client = Client('bos1-vcd-sp-static-202-34.eng.vmware.com',
                verify_ssl_certs=False)
client.set_highest_supported_version()
client.set_credentials(BasicLoginCredentials('usr1', 'org1', 'ca$hc0w'))

org = Org(client, resource=client.get_org())
vdc = VDC(client, resource=org.get_vdc('vdc1'))

for resource in vdc.list_resources():
    print('%s%s' % (resource['name'].ljust(40), resource['type']))

client.logout()