Exemplo n.º 1
0
 def __init__(self, module):
     super(VMwareHostDatastore, self).__init__(module)
     self.gather_nfs_mount_info = self.module.params[
         'gather_nfs_mount_info']
     self.gather_vmfs_mount_info = self.module.params[
         'gather_vmfs_mount_info']
     self.schema = self.module.params['schema']
     self.properties = self.module.params['properties']
     if self.module.params['show_tag']:
         self.vmware_client = VmwareRestClient(self.module)
Exemplo n.º 2
0
    def properties_facts(self):
        ansible_facts = self.to_json(self.host, self.params.get('properties'))
        if self.params.get('show_tag'):
            vmware_client = VmwareRestClient(self.module)
            tag_info = {
                'tags': vmware_client.get_tags_for_hostsystem(hostsystem_mid=self.host._moId)
            }
            ansible_facts.update(tag_info)

        self.module.exit_json(changed=False, ansible_facts=ansible_facts)
Exemplo n.º 3
0
def main():
    argument_spec = VmwareRestClient.vmware_client_argument_spec()
    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True)

    vmware_category_facts = VmwareCategoryFactsManager(module)
    vmware_category_facts.get_all_tag_categories()
Exemplo n.º 4
0
def main():
    argument_spec = VmwareRestClient.vmware_client_argument_spec()
    argument_spec.update(
        tag_names=dict(type='list', required=True, elements='raw'),
        state=dict(type='str',
                   choices=['absent', 'add', 'present', 'remove', 'set'],
                   default='add'),
        moid=dict(type='str'),
        object_name=dict(type='str'),
        object_type=dict(type='str',
                         required=True,
                         choices=[
                             'VirtualMachine', 'Datacenter',
                             'ClusterComputeResource', 'HostSystem',
                             'DistributedVirtualSwitch',
                             'DistributedVirtualPortgroup', 'Datastore',
                             'ResourcePool', 'Folder', 'DatastoreCluster'
                         ]),
    )
    module = AnsibleModule(argument_spec=argument_spec,
                           mutually_exclusive=[
                               ('moid', 'object_name'),
                           ],
                           required_one_of=[
                               ['moid', 'object_name'],
                           ])

    vmware_tag_manager = VmwareTagManager(module)
    vmware_tag_manager.ensure_state()
Exemplo n.º 5
0
def main():
    argument_spec = VmwareRestClient.vmware_client_argument_spec()
    argument_spec.update(
        library_name=dict(type='str', required=True),
        library_description=dict(type='str', required=False),
        library_type=dict(type='str',
                          required=False,
                          choices=['local', 'subscribed'],
                          default='local'),
        datastore_name=dict(type='str', required=False, aliases=['datastore']),
        state=dict(type='str',
                   choices=['present', 'absent'],
                   default='present',
                   required=False),
        subscription_url=dict(type='str', default='', required=False),
        ssl_thumbprint=dict(type='str', default='', required=False),
        update_on_demand=dict(type='bool', default=False, required=False),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=[
            ('library_type', 'subscribed', ['subscription_url']),
        ],
    )

    vmware_contentlib_create = VmwareContentLibCreate(module)
    vmware_contentlib_create.process_state()
Exemplo n.º 6
0
def main():
    argument_spec = VmwareRestClient.vmware_client_argument_spec()
    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True)

    vmware_tag_info = VmTagInfoManager(module)
    vmware_tag_info.get_all_tags()
Exemplo n.º 7
0
    def all_facts(self):
        ansible_facts = {}
        ansible_facts.update(self.get_cpu_facts())
        ansible_facts.update(self.get_memory_facts())
        ansible_facts.update(self.get_datastore_facts())
        ansible_facts.update(self.get_network_facts())
        ansible_facts.update(self.get_system_facts())
        ansible_facts.update(self.get_vsan_facts())
        ansible_facts.update(self.get_cluster_facts())
        if self.params.get('show_tag'):
            vmware_client = VmwareRestClient(self.module)
            tag_info = {
                'tags': vmware_client.get_tags_for_hostsystem(hostsystem_mid=self.host._moId)
            }
            ansible_facts.update(tag_info)

        self.module.exit_json(changed=False, ansible_facts=ansible_facts)
Exemplo n.º 8
0
def main():
    argument_spec = VmwareRestClient.vmware_client_argument_spec()
    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True)
    if module._name == 'vmware_tag_facts':
        module.deprecate("The 'vmware_tag_facts' module has been renamed to 'vmware_tag_info'", version='2.13')

    vmware_tag_info = VmTagInfoManager(module)
    vmware_tag_info.get_all_tags()
Exemplo n.º 9
0
def main():
    argument_spec = VmwareRestClient.vmware_client_argument_spec()
    argument_spec.update(cluster_name=dict(type='str', required=True), )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=False,
    )

    vmware_namespace_cluster_manage = VmwareNamespaceClusterVdsManage(module)
    vmware_namespace_cluster_manage.get_cluster_info()
def main():
    argument_spec = VmwareRestClient.vmware_client_argument_spec()
    argument_spec.update(library_id=dict(type='str', required=False), )
    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True)

    vmware_contentlib_info = VmwareContentLibInfo(module)
    if module.params.get('library_id'):
        vmware_contentlib_info.get_content_lib_details(
            module.params['library_id'])
    else:
        vmware_contentlib_info.get_all_content_libs()
Exemplo n.º 11
0
def main():
    argument_spec = VmwareRestClient.vmware_client_argument_spec()
    argument_spec.update(
        encryption_key=dict(type='str', required=False),
        description=dict(type='str', required=False),
        decryption_key=dict(type='str', required=False),
        api=dict(type='str',
                 required=False,
                 choices=['list', 'export', 'import', 'validate']),
        profiles=dict(type='str', required=False),
        config_path=dict(type='str', required=False),
    )
    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True)
    result = {'failed': False, 'changed': False}
    vmware_vc_infra_profile = VcenterProfile(module)
    vmware_vc_version = VcVersionChecker(module)
    vmware_vc_version.check_vc_version()

    if module.params['api'].lower() == "list":
        if module.check_mode:
            result.update(
                changed=False,
                desired_operation='list_vc_profile_configs',
            )
            module.exit_json(**result)
        vmware_vc_infra_profile.list_vc_infraprofile_configs()
    if module.params['api'].lower() == "export":
        if module.check_mode:
            result.update(
                changed=False,
                desired_operation='export_vc_profile_configs',
            )
            module.exit_json(**result)
        vmware_vc_infra_profile.vc_export_profile_task()

    if module.params['api'].lower() == "import":
        if module.check_mode:
            result.update(
                changed=True,
                desired_operation='import_vc_profile_configs',
            )
            module.exit_json(**result)
        vmware_vc_infra_profile.vc_import_profile_task()

    if module.params['api'].lower() == "validate":
        if module.check_mode:
            result.update(
                changed=True,
                desired_operation='import_vc_profile_configs',
            )
            module.exit_json(**result)
        vmware_vc_infra_profile.vc_validate_profile_task()
Exemplo n.º 12
0
def main():
    argument_spec = VmwareRestClient.vmware_client_argument_spec()
    argument_spec.update(
        tag_name=dict(type='str', required=True),
        tag_description=dict(type='str', default='', required=False),
        category_id=dict(type='str', required=False),
        state=dict(type='str', choices=['present', 'absent'], default='present', required=False),
    )
    module = AnsibleModule(argument_spec=argument_spec)

    vmware_tag = VmwareTag(module)
    vmware_tag.ensure_state()
Exemplo n.º 13
0
def main():
    argument_spec = VmwareRestClient.vmware_client_argument_spec()
    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True)
    if module._name in ('vmware_tag_facts',
                        'community.vmware.vmware_tag_facts'):
        module.deprecate(
            "The 'vmware_tag_facts' module has been renamed to 'vmware_tag_info'",
            version='3.0.0',
            collection_name='community.vmware')  # was Ansible 2.13

    vmware_tag_info = VmTagInfoManager(module)
    vmware_tag_info.get_all_tags()
class VmwareDatacenterInfo(PyVmomi):
    def __init__(self, module):
        super(VmwareDatacenterInfo, self).__init__(module)
        if self.params.get('show_tag'):
            self.vmware_client = VmwareRestClient(self.module)

    def get_datacenter_info(self):
        self.datacenter_name = self.params.get('datacenter')
        results = dict(
            changed=False,
            datacenter_info=[],
        )

        datacenter_objs = self.get_managed_objects_properties(
            vim_type=vim.Datacenter, properties=['name'])
        dcs = []
        for dc_obj in datacenter_objs:
            if len(dc_obj.propSet) == 1:
                if self.datacenter_name is not None:
                    if dc_obj.propSet[0].val == to_native(
                            self.datacenter_name):
                        dcs.append(dc_obj.obj)
                        continue
                else:
                    dcs.append(dc_obj.obj)

        for obj in dcs:
            if obj is None:
                continue
            temp_dc = dict(
                name=obj.name,
                moid=obj._moId,
            )
            if self.module.params['schema'] == 'summary':
                temp_dc.update(
                    dict(
                        config_status=obj.configStatus,
                        overall_status=obj.overallStatus,
                    ))
            else:
                temp_dc.update(self.to_json(obj,
                                            self.params.get('properties')))
            if self.params.get('show_tag'):
                temp_dc.update({
                    'tags':
                    self.vmware_client.get_tags_for_datacenter(
                        datacenter_mid=obj._moId)
                })

            results['datacenter_info'].append(temp_dc)
        self.module.exit_json(**results)
def main():
    argument_spec = VmwareRestClient.vmware_client_argument_spec()
    argument_spec.update(
        tag_names=dict(type='list', required=True),
        state=dict(type='str', choices=['absent', 'add', 'present', 'remove', 'set'], default='add'),
        object_name=dict(type='str', required=True),
        object_type=dict(type='str', required=True, choices=['VirtualMachine', 'Datacenter', 'ClusterComputeResource',
                                                             'HostSystem', 'DistributedVirtualSwitch',
                                                             'DistributedVirtualPortgroup']),
    )
    module = AnsibleModule(argument_spec=argument_spec)

    vmware_tag_manager = VmwareTagManager(module)
    vmware_tag_manager.ensure_state()
def main():
    argument_spec = VmwareRestClient.vmware_client_argument_spec()
    argument_spec.update(
        log_level=dict(type='str',
                       choices=[
                           'debug',
                           'info',
                           'normal',
                       ],
                       default='normal'),
        template=dict(type='str',
                      aliases=['ovf', 'ovf_template', 'template_src'],
                      required=True),
        library=dict(type='str',
                     aliases=['content_library', 'content_library_src'],
                     required=False),
        name=dict(type='str', aliases=['vm_name'], required=True),
        datacenter=dict(type='str', required=True),
        datastore=dict(type='str', required=False),
        datastore_cluster=dict(type='str', required=False),
        folder=dict(type='str', default='vm'),
        host=dict(type='str', required=False),
        resource_pool=dict(type='str', required=False),
        cluster=dict(type='str', required=False),
        storage_provisioning=dict(
            type='str',
            choices=['thin', 'thick', 'eagerZeroedThick', 'eagerzeroedthick'],
            default='thin',
            fallback=(env_fallback, ['VMWARE_STORAGE_PROVISIONING'])),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_one_of=[
            ['datastore', 'datastore_cluster'],
            ['host', 'cluster'],
        ],
    )

    result = {'failed': False, 'changed': False}
    vmware_contentlib_create = VmwareContentDeployOvfTemplate(module)
    if module.check_mode:
        result.update(
            vm_name=module.params['name'],
            changed=True,
            desired_operation='Create VM with PowerOff State',
        )
        module.exit_json(**result)
    vmware_contentlib_create.deploy_vm_from_ovf_template()
Exemplo n.º 17
0
def main():
    argument_spec = VmwareRestClient.vmware_client_argument_spec()
    argument_spec.update(
        state=dict(type='str',
                   default='present',
                   choices=['present', 'poweredon']),
        template=dict(type='str', aliases=['template_src'], required=True),
        content_library=dict(type='str',
                             aliases=['content_library_src'],
                             required=False),
        name=dict(type='str', required=True, aliases=['vm_name']),
        datacenter=dict(type='str', required=True),
        datastore=dict(type='str', required=True),
        folder=dict(type='str', required=True),
        host=dict(type='str', required=True),
        resource_pool=dict(type='str', required=False),
        cluster=dict(type='str', required=False),
    )
    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True)
    result = {'failed': False, 'changed': False}
    pyv = PyVmomi(module=module)
    vm = pyv.get_vm()
    if vm:
        module.exit_json(changed=False,
                         vm_deploy_info=dict(
                             msg="Virtual Machine '%s' already Exists." %
                             module.params['name'],
                             vm_id=vm._moId,
                         ))
    vmware_contentlib_create = VmwareContentDeployTemplate(module)
    if module.params['state'] in ['present']:
        if module.check_mode:
            result.update(
                vm_name=module.params['name'],
                changed=True,
                desired_operation='Create VM with PowerOff State',
            )
            module.exit_json(**result)
        vmware_contentlib_create.deploy_vm_from_template()
    if module.params['state'] == 'poweredon':
        if module.check_mode:
            result.update(
                vm_name=module.params['name'],
                changed=True,
                desired_operation='Create VM with PowerON State',
            )
            module.exit_json(**result)
        vmware_contentlib_create.deploy_vm_from_template(power_on=True)
Exemplo n.º 18
0
def main():
    argument_spec = VmwareRestClient.vmware_client_argument_spec()
    argument_spec.update(
        object_name=dict(),
        object_moid=dict(),
        new_name=dict(aliases=['object_new_name'], required=True),
        object_type=dict(type='str', required=True),
    )
    module = AnsibleModule(argument_spec=argument_spec,
                           mutually_exclusive=[
                               ['object_name', 'object_moid'],
                           ])

    vmware_object_rename = VmwareObjectRename(module)
    vmware_object_rename.ensure_state()
def main():
    argument_spec = VmwareRestClient.vmware_client_argument_spec()
    argument_spec.update(
        state=dict(type='str',
                   default='present',
                   choices=['present', 'poweredon']),
        template=dict(type='str', aliases=['template_src'], required=True),
        content_library=dict(type='str',
                             aliases=['content_library_src'],
                             required=False),
        name=dict(type='str', required=True, aliases=['vm_name']),
        datacenter=dict(type='str', required=True),
        datastore=dict(type='str', required=False),
        datastore_cluster=dict(type='str', required=False),
        folder=dict(type='str', required=True),
        host=dict(type='str', required=False),
        resource_pool=dict(type='str', required=False),
        cluster=dict(type='str', required=False),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_one_of=[
            ['datastore', 'datastore_cluster'],
        ],
    )
    result = {'failed': False, 'changed': False}

    vmware_contentlib_create = VmwareContentDeployTemplate(module)
    if module.params['state'] in ['present']:
        if module.check_mode:
            result.update(
                vm_name=module.params['name'],
                changed=True,
                desired_operation='Create VM with PowerOff State',
            )
            module.exit_json(**result)
        vmware_contentlib_create.deploy_vm_from_template()
    if module.params['state'] == 'poweredon':
        if module.check_mode:
            result.update(
                vm_name=module.params['name'],
                changed=True,
                desired_operation='Create VM with PowerON State',
            )
            module.exit_json(**result)
        vmware_contentlib_create.deploy_vm_from_template(power_on=True)
Exemplo n.º 20
0
def main():
    argument_spec = VmwareRestClient.vmware_client_argument_spec()
    argument_spec.update(
        object_name=dict(),
        object_moid=dict(),
        new_name=dict(aliases=['object_new_name'], required=True),
        object_type=dict(type='str', required=True, choices=['ClusterComputeResource', 'Cluster', 'Datacenter',
                                                             'Datastore', 'Folder', 'Network', 'ResourcePool', 'VM',
                                                             'VirtualMachine'])
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        mutually_exclusive=[
            ['object_name', 'object_moid'],
        ]
    )

    vmware_object_rename = VmwareObjectRename(module)
    vmware_object_rename.ensure_state()
def main():
    argument_spec = VmwareRestClient.vmware_client_argument_spec()
    argument_spec.update(
        category_name=dict(type='str', required=True),
        category_description=dict(type='str', default='', required=False),
        category_cardinality=dict(type='str',
                                  choices=["multiple", "single"],
                                  default="multiple"),
        new_category_name=dict(type='str'),
        state=dict(type='str',
                   choices=['present', 'absent'],
                   default='present'),
        associable_object_types=dict(
            type='list',
            choices=[
                'All objects',
                'Cluster',
                'Content Library',
                'Datacenter',
                'Datastore',
                'Datastore Cluster',
                'Distributed Port Group',
                'Distributed Switch',
                'Folder',
                'Host',
                'Library item',
                'Network',
                'Host Network',
                'Opaque Network',
                'Resource Pool',
                'vApp',
                'Virtual Machine',
            ],
            elements='str',
        ),
    )
    module = AnsibleModule(argument_spec=argument_spec)

    vmware_category = VmwareCategory(module)
    vmware_category.ensure_state()
def main():
    argument_spec = VmwareRestClient.vmware_client_argument_spec()
    argument_spec.update(
        ovf_template=dict(type='str',
                          aliases=['template_src', 'ovf'],
                          required=True),
        name=dict(type='str', required=True, aliases=['vm_name']),
        datacenter=dict(type='str', required=True),
        datastore=dict(type='str', required=True),
        folder=dict(type='str', required=True),
        host=dict(type='str', required=True),
        resource_pool=dict(type='str', required=True),
        cluster=dict(type='str', required=False),
        storage_provisioning=dict(
            type='str',
            required=False,
            choices=['thin', 'thick', 'eagerZeroedThick'],
            default=None),
    )
    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True)
    result = {'failed': False, 'changed': False}
    pyv = PyVmomi(module=module)
    vm = pyv.get_vm()
    if vm:
        module.exit_json(changed=False,
                         vm_deploy_info=dict(
                             msg="Virtual Machine '%s' already Exists." %
                             module.params['name'],
                             vm_id=vm._moId,
                         ))
    vmware_contentlib_create = VmwareContentDeployOvfTemplate(module)
    if module.check_mode:
        result.update(
            vm_name=module.params['name'],
            changed=True,
            desired_operation='Create VM with PowerOff State',
        )
        module.exit_json(**result)
    vmware_contentlib_create.deploy_vm_from_ovf_template()
Exemplo n.º 23
0
    def gather_cluster_info(self):
        """
        Gather information about cluster
        """
        results = dict(changed=False, clusters=dict())

        if self.schema == 'summary':
            for cluster in self.cluster_objs:
                # Default values
                ha_failover_level = None
                ha_restart_priority = None
                ha_vm_tools_monitoring = None
                ha_vm_min_up_time = None
                ha_vm_max_failures = None
                ha_vm_max_failure_window = None
                ha_vm_failure_interval = None
                enabled_vsan = False
                vsan_auto_claim_storage = False
                hosts = []

                # Hosts
                for host in cluster.host:
                    hosts.append({
                        'name':
                        host.name,
                        'folder':
                        self.get_vm_path(self.content, host),
                    })

                # HA
                das_config = cluster.configurationEx.dasConfig
                if das_config.admissionControlPolicy:
                    ha_failover_level = das_config.admissionControlPolicy.failoverLevel
                if das_config.defaultVmSettings:
                    ha_restart_priority = das_config.defaultVmSettings.restartPriority,
                    ha_vm_tools_monitoring = das_config.defaultVmSettings.vmToolsMonitoringSettings.vmMonitoring,
                    ha_vm_min_up_time = das_config.defaultVmSettings.vmToolsMonitoringSettings.minUpTime,
                    ha_vm_max_failures = das_config.defaultVmSettings.vmToolsMonitoringSettings.maxFailures,
                    ha_vm_max_failure_window = das_config.defaultVmSettings.vmToolsMonitoringSettings.maxFailureWindow,
                    ha_vm_failure_interval = das_config.defaultVmSettings.vmToolsMonitoringSettings.failureInterval,

                # DRS
                drs_config = cluster.configurationEx.drsConfig

                # VSAN
                if hasattr(cluster.configurationEx, 'vsanConfigInfo'):
                    vsan_config = cluster.configurationEx.vsanConfigInfo
                    enabled_vsan = vsan_config.enabled
                    vsan_auto_claim_storage = vsan_config.defaultConfig.autoClaimStorage

                tag_info = []
                if self.params.get('show_tag'):
                    vmware_client = VmwareRestClient(self.module)
                    tag_info = vmware_client.get_tags_for_cluster(
                        cluster_mid=cluster._moId)

                resource_summary = self.to_json(cluster.GetResourceUsage())
                if '_vimtype' in resource_summary:
                    del resource_summary['_vimtype']

                results['clusters'][unquote(cluster.name)] = dict(
                    hosts=hosts,
                    enable_ha=das_config.enabled,
                    ha_failover_level=ha_failover_level,
                    ha_vm_monitoring=das_config.vmMonitoring,
                    ha_host_monitoring=das_config.hostMonitoring,
                    ha_admission_control_enabled=das_config.
                    admissionControlEnabled,
                    ha_restart_priority=ha_restart_priority,
                    ha_vm_tools_monitoring=ha_vm_tools_monitoring,
                    ha_vm_min_up_time=ha_vm_min_up_time,
                    ha_vm_max_failures=ha_vm_max_failures,
                    ha_vm_max_failure_window=ha_vm_max_failure_window,
                    ha_vm_failure_interval=ha_vm_failure_interval,
                    enabled_drs=drs_config.enabled,
                    drs_enable_vm_behavior_overrides=drs_config.
                    enableVmBehaviorOverrides,
                    drs_default_vm_behavior=drs_config.defaultVmBehavior,
                    drs_vmotion_rate=drs_config.vmotionRate,
                    enabled_vsan=enabled_vsan,
                    vsan_auto_claim_storage=vsan_auto_claim_storage,
                    tags=tag_info,
                    resource_summary=resource_summary,
                    moid=cluster._moId,
                    datacenter=get_parent_datacenter(cluster).name)
        else:
            for cluster in self.cluster_objs:
                results['clusters'][unquote(cluster.name)] = self.to_json(
                    cluster, self.properties)

        self.module.exit_json(**results)
Exemplo n.º 24
0
class VmwareStoragePolicyManager(SPBM):
    def __init__(self, module):
        super(VmwareStoragePolicyManager, self).__init__(module)
        self.rest_client = VmwareRestClient(module)

    #
    # MOB METHODS
    #
    # These will generate the individual items with the following expected structure (see
    # https://github.com/vmware/pyvmomi/blob/master/pyVmomi/PbmObjects.py):
    #
    # PbmProfile: array
    #   - name:        string
    #     description: string
    #     constraints: PbmCapabilityConstraints
    #       subProfiles: ArrayOfPbmCapabilitySubProfile
    #         - name:       string
    #           capability: ArrayOfPbmCapabilityInstance
    #             - constraint: ArrayOfCapabilityConstraintInstance
    #               - id: string
    #                 value: anyType
    #                   values: arrayOfStrings
    #                     - tags
    #
    #
    def create_mob_tag_values(self, tags):
        return pbm.capability.types.DiscreteSet(values=tags)

    def create_mob_capability_property_instance(self, tag_id, tag_operator,
                                                tags):
        return pbm.capability.PropertyInstance(
            id=tag_id,
            operator=tag_operator,
            value=self.create_mob_tag_values(tags))

    def create_mob_capability_constraint_instance(self, tag_id, tag_operator,
                                                  tags):
        return pbm.capability.ConstraintInstance(propertyInstance=[
            self.create_mob_capability_property_instance(
                tag_id, tag_operator, tags)
        ])

    def create_mob_capability_metadata_uniqueid(self, tag_category):
        return pbm.capability.CapabilityMetadata.UniqueId(
            namespace="http://www.vmware.com/storage/tag", id=tag_category)

    def create_mob_capability_instance(self, tag_id, tag_operator, tags,
                                       tag_category):
        return pbm.capability.CapabilityInstance(
            id=self.create_mob_capability_metadata_uniqueid(tag_category),
            constraint=[
                self.create_mob_capability_constraint_instance(
                    tag_id, tag_operator, tags)
            ])

    def create_mob_capability_constraints_subprofile(self, tag_id,
                                                     tag_operator, tags,
                                                     tag_category):
        return pbm.profile.SubProfileCapabilityConstraints.SubProfile(
            name="Tag based placement",
            capability=[
                self.create_mob_capability_instance(tag_id, tag_operator, tags,
                                                    tag_category)
            ])

    def create_mob_capability_subprofile(self, tag_id, tag_operator, tags,
                                         tag_category):
        return pbm.profile.SubProfileCapabilityConstraints(subProfiles=[
            self.create_mob_capability_constraints_subprofile(
                tag_id, tag_operator, tags, tag_category)
        ])

    def create_mob_pbm_update_spec(self, tag_id, tag_operator, tags,
                                   tag_category, description):
        return pbm.profile.CapabilityBasedProfileUpdateSpec(
            description=description,
            constraints=self.create_mob_capability_subprofile(
                tag_id, tag_operator, tags, tag_category))

    def create_mob_pbm_create_spec(self, tag_id, tag_operator, tags,
                                   tag_category, description, name):
        return pbm.profile.CapabilityBasedProfileCreateSpec(
            name=name,
            description=description,
            resourceType=pbm.profile.ResourceType(resourceType="STORAGE"),
            category="REQUIREMENT",
            constraints=self.create_mob_capability_subprofile(
                tag_id, tag_operator, tags, tag_category))

    def get_tag_constraints(self, capabilities):
        """
        Return tag constraints for a profile given its capabilities
        """
        tag_constraints = {}
        for capability in capabilities:
            for constraint in capability.constraint:
                if hasattr(constraint, 'propertyInstance'):
                    for propertyInstance in constraint.propertyInstance:
                        if hasattr(propertyInstance.value, 'values'):
                            tag_constraints['id'] = propertyInstance.id
                            tag_constraints[
                                'values'] = propertyInstance.value.values
                            tag_constraints[
                                'operator'] = propertyInstance.operator

        return tag_constraints

    def get_profile_manager(self):
        self.get_spbm_connection()

        return self.spbm_content.profileManager

    def get_storage_policies(self, profile_manager):
        profile_ids = profile_manager.PbmQueryProfile(
            resourceType=pbm.profile.ResourceType(resourceType="STORAGE"),
            profileCategory="REQUIREMENT")
        profiles = []
        if profile_ids:
            profiles = profile_manager.PbmRetrieveContent(
                profileIds=profile_ids)

        return profiles

    def format_profile(self, profile):
        formatted_profile = {
            'name': profile.name,
            'id': profile.profileId.uniqueId,
            'description': profile.description
        }

        return formatted_profile

    def format_tag_mob_id(self, tag_category):
        return "com.vmware.storage.tag." + tag_category + ".property"

    def format_results_and_exit(self, results, policy, changed):
        results['vmware_vm_storage_policy'] = self.format_profile(policy)
        results['changed'] = changed

        self.module.exit_json(**results)

    def update_storage_policy(self, policy, pbm_client, results):
        expected_description = self.params.get('description')
        expected_tags = [self.params.get('tag_name')]
        expected_tag_category = self.params.get('tag_category')
        expected_tag_id = self.format_tag_mob_id(expected_tag_category)
        expected_operator = "NOT"
        if self.params.get('tag_affinity'):
            expected_operator = None

        needs_change = False

        if policy.description != expected_description:
            needs_change = True

        if hasattr(policy.constraints, 'subProfiles'):
            for subprofile in policy.constraints.subProfiles:
                tag_constraints = self.get_tag_constraints(
                    subprofile.capability)
                if tag_constraints['id'] == expected_tag_id:
                    if tag_constraints['values'] != expected_tags:
                        needs_change = True
                else:
                    needs_change = True

                if tag_constraints['operator'] != expected_operator:
                    needs_change = True
        else:
            needs_change = True

        if needs_change:
            pbm_client.PbmUpdate(profileId=policy.profileId,
                                 updateSpec=self.create_mob_pbm_update_spec(
                                     expected_tag_id, expected_operator,
                                     expected_tags, expected_tag_category,
                                     expected_description))

        self.format_results_and_exit(results, policy, needs_change)

    def remove_storage_policy(self, policy, pbm_client, results):
        pbm_client.PbmDelete(profileId=[policy.profileId])

        self.format_results_and_exit(results, policy, True)

    def create_storage_policy(self, policy, pbm_client, results):
        profile_ids = pbm_client.PbmCreate(
            createSpec=self.create_mob_pbm_create_spec(
                self.format_tag_mob_id(self.params.get('tag_category')), None,
                [self.params.get('tag_name')], self.params.get('tag_category'),
                self.params.get('description'), self.params.get('name')))

        policy = pbm_client.PbmRetrieveContent(profileIds=[profile_ids])

        self.format_results_and_exit(results, policy[0], True)

    def ensure_state(self):
        client = self.get_profile_manager()
        policies = self.get_storage_policies(client)
        policy_name = self.params.get('name')
        results = dict(changed=False, vmware_vm_storage_policy={})

        if self.params.get('state') == 'present':
            if self.params.get('tag_category') is None:
                self.module.fail_json(
                    msg="tag_category is required when 'state' is 'present'")

            if self.params.get('tag_name') is None:
                self.module.fail_json(
                    msg="tag_name is required when 'state' is 'present'")

            # ensure if the category exists
            category_result = self.rest_client.get_category_by_name(
                self.params.get('tag_category'))
            if category_result is None:
                self.module.fail_json(
                    msg="%s is not found in vCenter Server tag categories" %
                    self.params.get('tag_category'))

            # ensure if the tag exists
            tag_result = self.rest_client.get_tag_by_category(
                self.params.get('tag_name'), self.params.get('tag_category'))
            if tag_result is None:
                self.module.fail_json(
                    msg="%s is not found in vCenter Server tags" %
                    self.params.get('tag_name'))

            # loop through and update the first match
            for policy in policies:
                if policy.name == policy_name:
                    self.update_storage_policy(policy, client, results)

            # if we didn't exit by now create the profile
            self.create_storage_policy(policy, client, results)

        if self.params.get('state') == 'absent':
            # loop through and delete the first match
            for policy in policies:
                if policy.name == policy_name:
                    self.remove_storage_policy(policy, client, results)

            # if we didn't exit by now exit without changing anything
            self.module.exit_json(**results)
Exemplo n.º 25
0
class VMwareHostDatastore(PyVmomi):
    """ This class populates the datastore list """
    def __init__(self, module):
        super(VMwareHostDatastore, self).__init__(module)
        self.gather_nfs_mount_info = self.module.params[
            'gather_nfs_mount_info']
        self.gather_vmfs_mount_info = self.module.params[
            'gather_vmfs_mount_info']
        self.schema = self.module.params['schema']
        self.properties = self.module.params['properties']
        if self.module.params['show_tag']:
            self.vmware_client = VmwareRestClient(self.module)

    def check_datastore_host(self, esxi_host, datastore):
        """ Get all datastores of specified ESXi host """
        esxi = self.find_hostsystem_by_name(esxi_host)
        if esxi is None:
            self.module.fail_json(msg="Failed to find ESXi hostname %s " %
                                  esxi_host)
        storage_system = esxi.configManager.storageSystem
        host_file_sys_vol_mount_info = storage_system.fileSystemVolumeInfo.mountInfo
        for host_mount_info in host_file_sys_vol_mount_info:
            if host_mount_info.volume.name == datastore:
                return host_mount_info
        return None

    def build_datastore_list(self, datastore_list):
        """ Build list with datastores """
        datastores = list()
        for datastore in datastore_list:
            if self.schema == 'summary':
                summary = datastore.summary
                datastore_summary = dict()
                datastore_summary['accessible'] = summary.accessible
                datastore_summary['capacity'] = summary.capacity
                datastore_summary['name'] = summary.name
                datastore_summary['freeSpace'] = summary.freeSpace
                datastore_summary['maintenanceMode'] = summary.maintenanceMode
                datastore_summary[
                    'multipleHostAccess'] = summary.multipleHostAccess
                datastore_summary['type'] = summary.type
                if self.gather_nfs_mount_info or self.gather_vmfs_mount_info:
                    if self.gather_nfs_mount_info and summary.type.startswith(
                            "NFS"):
                        # get mount info from the first ESXi host attached to this NFS datastore
                        host_mount_info = self.check_datastore_host(
                            summary.datastore.host[0].key.name, summary.name)
                        datastore_summary[
                            'nfs_server'] = host_mount_info.volume.remoteHost
                        datastore_summary[
                            'nfs_path'] = host_mount_info.volume.remotePath
                    if self.gather_vmfs_mount_info and summary.type == "VMFS":
                        # get mount info from the first ESXi host attached to this VMFS datastore
                        host_mount_info = self.check_datastore_host(
                            summary.datastore.host[0].key.name, summary.name)
                        datastore_summary[
                            'vmfs_blockSize'] = host_mount_info.volume.blockSize
                        datastore_summary[
                            'vmfs_version'] = host_mount_info.volume.version
                        datastore_summary[
                            'vmfs_uuid'] = host_mount_info.volume.uuid
                # uncommitted is optional / not always set
                if not summary.uncommitted:
                    summary.uncommitted = 0
                datastore_summary['uncommitted'] = summary.uncommitted
                datastore_summary['url'] = summary.url
                # Calculated values
                datastore_summary[
                    'provisioned'] = summary.capacity - summary.freeSpace + summary.uncommitted
                datastore_summary['datastore_cluster'] = 'N/A'
                if isinstance(datastore.parent, vim.StoragePod):
                    datastore_summary[
                        'datastore_cluster'] = datastore.parent.name

                if self.module.params['show_tag']:
                    datastore_summary[
                        'tags'] = self.vmware_client.get_tags_for_datastore(
                            datastore._moId)

                if self.module.params['name']:
                    if datastore_summary['name'] == self.module.params['name']:
                        datastores.extend([datastore_summary])
                else:
                    datastores.extend([datastore_summary])
            else:
                temp_ds = self.to_json(datastore, self.properties)
                if self.module.params['show_tag']:
                    temp_ds.update({
                        'tags':
                        self.vmware_client.get_tags_for_datastore(
                            datastore._moId)
                    })
                if self.module.params['name']:
                    if datastore.name == self.module.params['name']:
                        datastores.extend(([temp_ds]))
                else:
                    datastores.extend(([temp_ds]))

        return datastores
Exemplo n.º 26
0
 def __init__(self, module):
     super(VmwareStoragePolicyManager, self).__init__(module)
     self.rest_client = VmwareRestClient(module)
Exemplo n.º 27
0
 def __init__(self, module):
     super(VmwareVmInfo, self).__init__(module)
     if self.module.params.get('show_tag'):
         self.vmware_client = VmwareRestClient(self.module)
Exemplo n.º 28
0
class VmwareVmInfo(PyVmomi):
    def __init__(self, module):
        super(VmwareVmInfo, self).__init__(module)
        if self.module.params.get('show_tag'):
            self.vmware_client = VmwareRestClient(self.module)

    def get_tag_info(self, vm_dynamic_obj):
        return self.vmware_client.get_tags_for_vm(vm_mid=vm_dynamic_obj._moId)

    def get_vm_attributes(self, vm):
        return dict((x.name, v.value) for x in self.custom_field_mgr
                    for v in vm.customValue if x.key == v.key)

    # https://github.com/vmware/pyvmomi-community-samples/blob/master/samples/getallvms.py
    def get_virtual_machines(self):
        """
        Get one/all virtual machines and related configurations information.
        """
        folder = self.params.get('folder')
        folder_obj = None
        if folder:
            folder_obj = self.content.searchIndex.FindByInventoryPath(folder)
            if not folder_obj:
                self.module.fail_json(msg="Failed to find folder specified by %(folder)s" % self.params)

        vm_name = self.params.get('vm_name')
        if vm_name:
            virtual_machine = find_vm_by_name(self.content, vm_name=vm_name, folder=folder_obj)
            if not virtual_machine:
                self.module.fail_json(msg="Failed to find virtual machine %s" % vm_name)
            else:
                virtual_machines = [virtual_machine]
        else:
            virtual_machines = get_all_objs(self.content, [vim.VirtualMachine], folder=folder_obj)
        _virtual_machines = []

        for vm in virtual_machines:
            _ip_address = ""
            summary = vm.summary
            if summary.guest is not None:
                _ip_address = summary.guest.ipAddress
                if _ip_address is None:
                    _ip_address = ""
            _mac_address = []
            all_devices = _get_vm_prop(vm, ('config', 'hardware', 'device'))
            if all_devices:
                for dev in all_devices:
                    if isinstance(dev, vim.vm.device.VirtualEthernetCard):
                        _mac_address.append(dev.macAddress)

            net_dict = {}
            vmnet = _get_vm_prop(vm, ('guest', 'net'))
            if vmnet:
                for device in vmnet:
                    net_dict[device.macAddress] = dict()
                    net_dict[device.macAddress]['ipv4'] = []
                    net_dict[device.macAddress]['ipv6'] = []
                    for ip_addr in device.ipAddress:
                        if "::" in ip_addr:
                            net_dict[device.macAddress]['ipv6'].append(ip_addr)
                        else:
                            net_dict[device.macAddress]['ipv4'].append(ip_addr)

            esxi_hostname = None
            esxi_parent = None
            if summary.runtime.host:
                esxi_hostname = summary.runtime.host.summary.config.name
                esxi_parent = summary.runtime.host.parent

            cluster_name = None
            if esxi_parent and isinstance(esxi_parent, vim.ClusterComputeResource):
                cluster_name = summary.runtime.host.parent.name

            vm_attributes = dict()
            if self.module.params.get('show_attribute'):
                vm_attributes = self.get_vm_attributes(vm)

            vm_tags = list()
            if self.module.params.get('show_tag'):
                vm_tags = self.get_tag_info(vm)

            vm_folder = PyVmomi.get_vm_path(content=self.content, vm_name=vm)
            datacenter = get_parent_datacenter(vm)
            datastore_url = list()
            datastore_attributes = ('name', 'url')
            if vm.config.datastoreUrl:
                for entry in vm.config.datastoreUrl:
                    datastore_url.append({key: getattr(entry, key) for key in dir(entry) if key in datastore_attributes})
            virtual_machine = {
                "guest_name": summary.config.name,
                "guest_fullname": summary.config.guestFullName,
                "power_state": summary.runtime.powerState,
                "ip_address": _ip_address,  # Kept for backward compatibility
                "mac_address": _mac_address,  # Kept for backward compatibility
                "uuid": summary.config.uuid,
                "vm_network": net_dict,
                "esxi_hostname": esxi_hostname,
                "datacenter": datacenter.name,
                "cluster": cluster_name,
                "attributes": vm_attributes,
                "tags": vm_tags,
                "folder": vm_folder,
                "moid": vm._moId,
                "datastore_url": datastore_url,
            }

            vm_type = self.module.params.get('vm_type')
            is_template = _get_vm_prop(vm, ('config', 'template'))
            if vm_type == 'vm' and not is_template:
                _virtual_machines.append(virtual_machine)
            elif vm_type == 'template' and is_template:
                _virtual_machines.append(virtual_machine)
            elif vm_type == 'all':
                _virtual_machines.append(virtual_machine)
        return _virtual_machines
Exemplo n.º 29
0
 def get_tag_info(self, vm_dynamic_obj):
     vmware_client = VmwareRestClient(self.module)
     return vmware_client.get_tags_for_vm(vm_mid=vm_dynamic_obj._moId)
def main():
    argument_spec = VmwareRestClient.vmware_client_argument_spec()
    argument_spec.update(
        cluster_distributed_switch=dict(type='str', required=False),
        cluster_name=dict(type='str', required=True),
        default_content_library=dict(type='str', required=False),
        dns_search_domains=dict(type='list', required=False),
        egress_cidrs=dict(type='list', required=False),
        ephemeral_storage_policy=dict(type='str', required=False),
        haproxy_ca_chain=dict(type='str', required=False),
        haproxy_management_ip=dict(type='str', required=False),
        haproxy_management_port=dict(type='str',
                                     required=False,
                                     default='5556'),
        haproxy_password=dict(type='str', required=False),
        haproxy_ip_range_list=dict(type='list', required=False),
        haproxy_username=dict(type='str', required=False),
        image_storage_policy=dict(type='str', required=False),
        ingress_cidrs=dict(type='list', required=False),
        management_address_count=dict(type='int', required=False, default=5),
        management_dns_servers=dict(type='list', required=False),
        management_gateway=dict(type='str', required=False),
        management_netmask=dict(type='str', required=False),
        management_ntp_servers=dict(type='list', required=False),
        management_port_group=dict(type='str', required=False),
        management_starting_address=dict(type='str', required=False),
        master_storage_policy=dict(type='str', required=False),
        network_provider=dict(
            type='str',
            required=True,
            choices=['VSPHERE_NETWORK', 'NSXT_CONTAINER_PLUGIN']),
        nsx_edge_cluster=dict(type='str', required=False),
        pod_cidrs=dict(type='list', required=False),
        workload_dns_servers=dict(type='list', required=False),
        workload_gateway=dict(type='str', required=False),
        workload_netmask=dict(type='str', required=False),
        workload_ntp_servers=dict(type='list', required=False),
        workload_portgroup=dict(type='str', required=False),
        workload_ip_range_list=dict(type='list', required=False),
        services_cidr=dict(type='str', required=False),
        supervisor_size=dict(type='str',
                             choices=['TINY', 'SMALL', 'MEDIUM', 'LARGE'],
                             required=False),
        state=dict(type='str',
                   choices=['present', 'absent'],
                   default='present',
                   required=False),
        # storage_policy_name=dict(type='str', required=False),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=[
            ('state', 'present', [
                'ephemeral_storage_policy', 'image_storage_policy',
                'management_dns_servers', 'management_gateway',
                'management_netmask', 'management_ntp_servers',
                'management_port_group', 'management_starting_address',
                'master_storage_policy', 'network_provider', 'services_cidr',
                'supervisor_size', 'workload_dns_servers',
                'workload_ntp_servers'
            ]),
            ('network_provider', 'VSPHERE_NETWORK', [
                'haproxy_ca_chain',
                'haproxy_management_ip',
                'haproxy_password',
                'haproxy_ip_range_list',
                'haproxy_username',
                'workload_dns_servers',
                'workload_gateway',
                'workload_portgroup',
                'workload_ip_range_list',
                'workload_netmask',
            ]),
            ('network_provider', 'NSXT_CONTAINER_PLUGIN', [
                'cluster_distributed_switch', 'egress_cidrs', 'ingress_cidrs',
                'nsx_edge_cluster', 'pod_cidrs'
            ]),
        ])

    vmware_namespace_cluster_manage = VmwareNamespaceClusterVdsManage(module)
    vmware_namespace_cluster_manage.process_state()