def __init__(self, module):
        """
        Constructor
        """
        super(VmwareTagManager, self).__init__(module)
        self.pyv = PyVmomi(module=module)

        self.object_type = self.params.get('object_type')
        self.object_name = self.params.get('object_name')
        self.managed_object = None

        if self.object_type == 'VirtualMachine':
            self.managed_object = self.pyv.get_vm_or_template(self.object_name)

        if self.object_type == 'Datacenter':
            self.managed_object = self.pyv.find_datacenter_by_name(
                self.object_name)

        if self.object_type == 'ClusterComputeResource':
            self.managed_object = self.pyv.find_cluster_by_name(
                self.object_name)

        if self.object_type == 'HostSystem':
            self.managed_object = self.pyv.find_hostsystem_by_name(
                self.object_name)

        if self.object_type == 'DistributedVirtualSwitch':
            self.managed_object = find_dvs_by_name(self.pyv.content,
                                                   self.object_name)
            self.object_type = 'VmwareDistributedVirtualSwitch'

        if self.object_type == 'DistributedVirtualPortgroup':
            dvs_name, pg_name = self.object_name.split(":", 1)
            dv_switch = find_dvs_by_name(self.pyv.content, dvs_name)
            if dv_switch is None:
                self.module.fail_json(
                    msg=
                    "A distributed virtual switch with name %s does not exist"
                    % dvs_name)
            self.managed_object = find_dvspg_by_name(dv_switch, pg_name)

        if self.managed_object is None:
            self.module.fail_json(
                msg="Failed to find the managed object for %s with type %s" %
                (self.object_name, self.object_type))

        if not hasattr(self.managed_object, '_moId'):
            self.module.fail_json(
                msg="Unable to find managed object id for %s managed object" %
                self.object_name)

        self.dynamic_managed_object = DynamicID(type=self.object_type,
                                                id=self.managed_object._moId)

        self.tag_service = self.api_client.tagging.Tag
        self.category_service = self.api_client.tagging.Category
        self.tag_association_svc = self.api_client.tagging.TagAssociation

        self.tag_names = self.params.get('tag_names')
Esempio n. 2
0
    def check_dvs_host_state(self):
        self.dv_switch = find_dvs_by_name(self.content, self.switch_name)

        if self.dv_switch is None:
            self.module.fail_json(msg="A distributed virtual switch %s "
                                  "does not exist" % self.switch_name)

        self.uplink_portgroup = self.find_dvs_uplink_pg()

        if self.uplink_portgroup is None:
            self.module.fail_json(msg="An uplink portgroup does not exist on"
                                  " the distributed virtual switch %s" %
                                  self.switch_name)

        self.host = self.find_host_attached_dvs()

        if self.host is None:
            # We still need the HostSystem object to add the host
            # to the distributed vswitch
            self.host = find_hostsystem_by_name(self.content,
                                                self.esxi_hostname)
            if self.host is None:
                self.module.fail_json(
                    msg="The esxi_hostname %s does not exist "
                    "in vCenter" % self.esxi_hostname)
            return 'absent'
        else:
            if self.check_uplinks():
                return 'present'
            else:
                return 'update'
Esempio n. 3
0
 def __init__(self, module):
     super(VMwareDvSwitchUplinkPortgroup, self).__init__(module)
     self.switch_name = self.module.params['switch']
     self.uplink_pg_name = self.params['name']
     self.uplink_pg_description = self.params['description']
     self.uplink_pg_reset = self.params['advanced'].get(
         'port_config_reset_at_disconnect')
     self.uplink_pg_block_ports = self.params['advanced'].get(
         'block_override')
     self.uplink_pg_vendor_conf = self.params['advanced'].get(
         'vendor_config_override')
     self.uplink_pg_vlan = self.params['advanced'].get('vlan_override')
     self.uplink_pg_netflow = self.params['advanced'].get(
         'netflow_override')
     self.uplink_pg_tf = self.params['advanced'].get(
         'traffic_filter_override')
     self.uplink_pg_vlan_trunk_range = self.params['vlan_trunk_range']
     self.uplink_pg_netflow_enabled = self.params['netflow_enabled']
     self.uplink_pg_block_all_ports = self.params['block_all_ports']
     self.lacp_status = self.params['lacp'].get('status')
     self.lacp_mode = self.params['lacp'].get('mode')
     self.dvs = find_dvs_by_name(self.content, self.switch_name)
     if self.dvs is None:
         self.module.fail_json(msg="Failed to find DVS %s" %
                               self.switch_name)
     self.support_mode = self.dvs.config.lacpApiVersion
Esempio n. 4
0
 def check_dvs(self):
     """Check if DVS is present"""
     self.dvs = find_dvs_by_name(self.content,
                                 self.switch_name,
                                 folder=self.folder_obj)
     if self.dvs is None:
         return 'absent'
     return 'present'
    def state_migrate_vss_vds(self):
        host_network_system = self.host_system.configManager.networkSystem

        dv_switch = find_dvs_by_name(self.content, self.migrate_switch_name)
        pg = find_dvspg_by_name(dv_switch, self.migrate_portgroup_name)

        config = vim.host.NetworkConfig()
        config.portgroup = [self.create_port_group_config()]
        config.vnic = [self.create_host_vnic_config(dv_switch.uuid, pg.key)]
        host_network_system.UpdateNetworkConfig(config, "modify")
        self.module.exit_json(changed=True)
    def check_nioc_state(self):
        self.dvs = find_dvs_by_name(self.content, self.switch)

        if self.dvs is None:
            self.module.fail_json(msg='DVS %s was not found.' % self.switch)
        else:
            if not self.dvs.config.networkResourceManagementEnabled:
                return 'absent'
            if self.version and self.dvs.config.networkResourceControlVersion != self.version:
                return 'version'

            # NIOC is enabled and the correct version, so return the state of the resources
            return self.check_resources()
    def check_resources(self):
        self.dvs = find_dvs_by_name(self.content, self.switch)
        if self.dvs is None:
            self.module.fail_json(msg="DVS named '%s' was not found" %
                                  self.switch)

        for resource in self.resources:
            if self.check_resource_state(resource) == 'update':
                self.resource_changes.append(resource)
                self.result['resources_changed'].append(resource['name'])

        if len(self.resource_changes) > 0:
            return 'update'
        return 'present'
    def check_vmk_current_state(self):
        self.host_system = find_hostsystem_by_name(self.content, self.esxi_hostname)

        for vnic in self.host_system.configManager.networkSystem.networkInfo.vnic:
            if vnic.device == self.device:
                # self.vnic = vnic
                if vnic.spec.distributedVirtualPort is None:
                    if vnic.portgroup == self.current_portgroup_name:
                        return "migrate_vss_vds"
                else:
                    dvs = find_dvs_by_name(self.content, self.current_switch_name)
                    if dvs is None:
                        return "migrated"
                    if vnic.spec.distributedVirtualPort.switchUuid == dvs.uuid:
                        return "migrate_vds_vss"
 def __init__(self, module):
     super(VMwareDvSwitchPvlans, self).__init__(module)
     self.switch_name = self.module.params['switch']
     if self.module.params['primary_pvlans']:
         self.primary_pvlans = self.module.params['primary_pvlans']
         if self.module.params['secondary_pvlans']:
             self.secondary_pvlans = self.module.params['secondary_pvlans']
         else:
             self.secondary_pvlans = None
         self.do_pvlan_sanity_checks()
     else:
         self.primary_pvlans = None
         self.secondary_pvlans = None
     self.dvs = find_dvs_by_name(self.content, self.switch_name)
     if self.dvs is None:
         self.module.fail_json(msg="Failed to find DVS %s" % self.switch_name)
Esempio n. 10
0
 def __init__(self, module):
     super(VMwareDvSwitchLacp, self).__init__(module)
     self.switch_name = self.module.params['switch']
     self.support_mode = self.module.params['support_mode']
     self.link_aggregation_groups = self.module.params[
         'link_aggregation_groups']
     if self.support_mode == 'basic' and (
             self.link_aggregation_groups
             and not (len(self.link_aggregation_groups) == 1
                      and self.link_aggregation_groups[0] == '')):
         self.module.fail_json(
             msg=
             "LAGs can only be configured if 'support_mode' is set to 'enhanced'!"
         )
     self.dvs = find_dvs_by_name(self.content, self.switch_name)
     if self.dvs is None:
         self.module.fail_json(msg="Failed to find DVS %s" %
                               self.switch_name)
 def __init__(self, module):
     super(VMwareVspanSession, self).__init__(module)
     self.switch = module.params['switch']
     self.name = module.params['name']
     self.session_type = module.params['session_type']
     self.enabled = module.params['enabled']
     self.state = module.params['state']
     self.description = module.params['description']
     self.source_port_transmitted = module.params['source_port_transmitted']
     self.source_port_received = module.params['source_port_received']
     self.destination_port = module.params['destination_port']
     self.encapsulation_vlan_id = module.params['encapsulation_vlan_id']
     self.strip_original_vlan = module.params['strip_original_vlan']
     self.mirrored_packet_length = module.params['mirrored_packet_length']
     self.normal_traffic_allowed = module.params['normal_traffic_allowed']
     self.sampling_rate = module.params['sampling_rate']
     self.dv_switch = find_dvs_by_name(self.content, self.switch)
     if self.dv_switch is None:
         self.module.fail_json(msg="There is no dvSwitch with the name: {0:s}.".format(self.switch))
     self.operation = None
     self.modified_ports = dict()
     self.deleted_session = None
     if module.params['source_vm_transmitted'] is not None:
         if (module.params['source_vm_transmitted']['name'] is None or
                 module.params['source_vm_transmitted']['nic_label'] is None):
             self.module.fail_json(msg="Please provide both VM name and NIC Label")
         self.source_vm_transmitted_name = module.params['source_vm_transmitted']['name']
         self.source_vm_transmitted_nic_label = module.params['source_vm_transmitted']['nic_label']
     if module.params['source_vm_received'] is not None:
         if (module.params['source_vm_received']['name'] is None or
                 module.params['source_vm_received']['nic_label'] is None):
             self.module.fail_json(msg="Please provide both VM name and NIC Label")
         self.source_vm_received_name = module.params['source_vm_received']['name']
         self.source_vm_received_nic_label = module.params['source_vm_received']['nic_label']
     if module.params['destination_vm'] is not None:
         if (module.params['destination_vm']['name'] is None or
                 module.params['destination_vm']['nic_label'] is None):
             self.module.fail_json(msg="Please provide both VM name and NIC Label")
         self.destination_vm_name = module.params['destination_vm']['name']
         self.destination_vm_nic_label = module.params['destination_vm']['nic_label']
    def __init__(self, module):
        super(DVSPortgroupFactsManager, self).__init__(module)
        self.dc_name = self.params['datacenter']
        self.dvs_name = self.params['dvswitch']

        datacenter = self.find_datacenter_by_name(self.dc_name)
        if datacenter is None:
            self.module.fail_json(msg="Failed to find the datacenter %s" %
                                  self.dc_name)
        if self.dvs_name:
            # User specified specific dvswitch name to gather information
            dvsn = find_dvs_by_name(self.content, self.dvs_name)
            if dvsn is None:
                self.module.fail_json(msg="Failed to find the dvswitch %s" %
                                      self.dvs_name)

            self.dvsls = [dvsn]
        else:
            # default behaviour, gather information about all dvswitches
            self.dvsls = get_all_objs(self.content,
                                      [vim.DistributedVirtualSwitch],
                                      folder=datacenter.networkFolder)
Esempio n. 13
0
    def host_vmk_update(self):
        """
        Update VMKernel with given parameters
        Returns: NA

        """
        changed = changed_settings = changed_vds = changed_services = \
            changed_service_vmotion = changed_service_mgmt = changed_service_ft = \
            changed_service_vsan = changed_service_prov = changed_service_rep = changed_service_rep_nfc = False
        changed_list = []
        results = dict(changed=False, msg='')

        results['tcpip_stack'] = self.tcpip_stack
        net_stack_instance_key = self.get_api_net_stack_instance(
            self.tcpip_stack)
        if self.vnic.spec.netStackInstanceKey != net_stack_instance_key:
            self.module.fail_json(
                msg=
                "The TCP/IP stack cannot be changed on an existing VMkernel adapter!"
            )

        # Check MTU
        results['mtu'] = self.mtu
        if self.vnic.spec.mtu != self.mtu:
            changed_settings = True
            changed_list.append("MTU")
            results['mtu_previous'] = self.vnic.spec.mtu

        # Check IPv4 settings
        results['ipv4'] = self.network_type
        results['ipv4_ip'] = self.ip_address
        results['ipv4_sm'] = self.subnet_mask
        if self.default_gateway:
            results['ipv4_gw'] = self.default_gateway
        else:
            results['ipv4_gw'] = "No override"
        if self.vnic.spec.ip.dhcp:
            if self.network_type == 'static':
                changed_settings = True
                changed_list.append("IPv4 settings")
                results['ipv4_previous'] = "DHCP"
        if not self.vnic.spec.ip.dhcp:
            if self.network_type == 'dhcp':
                changed_settings = True
                changed_list.append("IPv4 settings")
                results['ipv4_previous'] = "static"
            elif self.network_type == 'static':
                if self.ip_address != self.vnic.spec.ip.ipAddress:
                    changed_settings = True
                    changed_list.append("IP")
                    results['ipv4_ip_previous'] = self.vnic.spec.ip.ipAddress
                if self.subnet_mask != self.vnic.spec.ip.subnetMask:
                    changed_settings = True
                    changed_list.append("SM")
                    results['ipv4_sm_previous'] = self.vnic.spec.ip.subnetMask
                if self.default_gateway:
                    try:
                        if self.default_gateway != self.vnic.spec.ipRouteSpec.ipRouteConfig.defaultGateway:
                            changed_settings = True
                            changed_list.append("GW override")
                            results[
                                'ipv4_gw_previous'] = self.vnic.spec.ipRouteSpec.ipRouteConfig.defaultGateway
                    except AttributeError:
                        changed_settings = True
                        changed_list.append("GW override")
                        results['ipv4_gw_previous'] = "No override"
                else:
                    try:
                        if self.vnic.spec.ipRouteSpec.ipRouteConfig.defaultGateway:
                            changed_settings = True
                            changed_list.append("GW override")
                            results[
                                'ipv4_gw_previous'] = self.vnic.spec.ipRouteSpec.ipRouteConfig.defaultGateway
                    except AttributeError:
                        pass

        # Check virtual port (vSS or vDS)
        results['portgroup'] = self.port_group_name
        dvs_uuid = None
        if self.vswitch_name:
            results['switch'] = self.vswitch_name
            try:
                if self.vnic.spec.distributedVirtualPort.switchUuid:
                    changed_vds = True
                    changed_list.append("Virtual Port")
                    dvs_uuid = self.vnic.spec.distributedVirtualPort.switchUuid
            except AttributeError:
                pass
            if changed_vds:
                results['switch_previous'] = self.find_dvs_by_uuid(dvs_uuid)
                self.dv_switch_obj = find_dvs_by_name(
                    self.content, results['switch_previous'])
                results['portgroup_previous'] = self.find_dvspg_by_key(
                    self.dv_switch_obj,
                    self.vnic.spec.distributedVirtualPort.portgroupKey)
        elif self.vds_name:
            results['switch'] = self.vds_name
            try:
                if self.vnic.spec.distributedVirtualPort.switchUuid != self.dv_switch_obj.uuid:
                    changed_vds = True
                    changed_list.append("Virtual Port")
                    dvs_uuid = self.vnic.spec.distributedVirtualPort.switchUuid
            except AttributeError:
                changed_vds = True
                changed_list.append("Virtual Port")
            if changed_vds:
                results['switch_previous'] = self.find_dvs_by_uuid(dvs_uuid)
                results['portgroup_previous'] = self.vnic.spec.portgroup
                portgroups = self.get_all_port_groups_by_host(
                    host_system=self.esxi_host_obj)
                for portgroup in portgroups:
                    if portgroup.spec.name == self.vnic.spec.portgroup:
                        results['switch_previous'] = portgroup.spec.vswitchName

        results['services'] = self.create_enabled_services_string()
        # Check configuration of service types (only if default TCP/IP stack is used)
        if self.vnic.spec.netStackInstanceKey == 'defaultTcpipStack':
            service_type_vmks = self.get_all_vmks_by_service_type()
            if (self.enable_vmotion and self.vnic.device not in service_type_vmks['vmotion']) or \
                    (not self.enable_vmotion and self.vnic.device in service_type_vmks['vmotion']):
                changed_services = changed_service_vmotion = True

            if (self.enable_mgmt and self.vnic.device not in service_type_vmks['management']) or \
                    (not self.enable_mgmt and self.vnic.device in service_type_vmks['management']):
                changed_services = changed_service_mgmt = True

            if (self.enable_ft and self.vnic.device not in service_type_vmks['faultToleranceLogging']) or \
                    (not self.enable_ft and self.vnic.device in service_type_vmks['faultToleranceLogging']):
                changed_services = changed_service_ft = True

            if (self.enable_vsan and self.vnic.device not in service_type_vmks['vsan']) or \
                    (not self.enable_vsan and self.vnic.device in service_type_vmks['vsan']):
                changed_services = changed_service_vsan = True

            if (self.enable_provisioning and self.vnic.device not in service_type_vmks['vSphereProvisioning']) or \
                    (not self.enable_provisioning and self.vnic.device in service_type_vmks['vSphereProvisioning']):
                changed_services = changed_service_prov = True

            if (self.enable_replication and self.vnic.device not in service_type_vmks['vSphereReplication']) or \
                    (not self.enable_provisioning and self.vnic.device in service_type_vmks['vSphereReplication']):
                changed_services = changed_service_rep = True

            if (self.enable_replication_nfc and self.vnic.device not in service_type_vmks['vSphereReplicationNFC']) or \
                    (not self.enable_provisioning and self.vnic.device in service_type_vmks['vSphereReplicationNFC']):
                changed_services = changed_service_rep_nfc = True
            if changed_services:
                changed_list.append("services")

        if changed_settings or changed_vds or changed_services:
            changed = True
            if self.module.check_mode:
                changed_suffix = ' would be updated'
            else:
                changed_suffix = ' updated'
            if len(changed_list) > 2:
                message = ', '.join(changed_list[:-1]) + ', and ' + str(
                    changed_list[-1])
            elif len(changed_list) == 2:
                message = ' and '.join(changed_list)
            elif len(changed_list) == 1:
                message = changed_list[0]
            message = "VMkernel Adapter " + message + changed_suffix
            if changed_settings or changed_vds:
                vnic_config = vim.host.VirtualNic.Specification()
                ip_spec = vim.host.IpConfig()
                if self.network_type == 'dhcp':
                    ip_spec.dhcp = True
                else:
                    ip_spec.dhcp = False
                    ip_spec.ipAddress = self.ip_address
                    ip_spec.subnetMask = self.subnet_mask
                    if self.default_gateway:
                        vnic_config.ipRouteSpec = vim.host.VirtualNic.IpRouteSpec(
                        )
                        vnic_config.ipRouteSpec.ipRouteConfig = vim.host.IpRouteConfig(
                        )
                        vnic_config.ipRouteSpec.ipRouteConfig.defaultGateway = self.default_gateway
                    else:
                        vnic_config.ipRouteSpec = vim.host.VirtualNic.IpRouteSpec(
                        )
                        vnic_config.ipRouteSpec.ipRouteConfig = vim.host.IpRouteConfig(
                        )

                vnic_config.ip = ip_spec
                vnic_config.mtu = self.mtu

                if changed_vds:
                    if self.vswitch_name:
                        vnic_config.portgroup = self.port_group_name
                    elif self.vds_name:
                        vnic_config.distributedVirtualPort = vim.dvs.PortConnection(
                        )
                        vnic_config.distributedVirtualPort.switchUuid = self.dv_switch_obj.uuid
                        vnic_config.distributedVirtualPort.portgroupKey = self.port_group_obj.key

                try:
                    if not self.module.check_mode:
                        self.esxi_host_obj.configManager.networkSystem.UpdateVirtualNic(
                            self.vnic.device, vnic_config)
                except vim.fault.NotFound as not_found:
                    self.module.fail_json(
                        msg=
                        "Failed to update vmk as virtual network adapter cannot be found %s"
                        % to_native(not_found.msg))
                except vim.fault.HostConfigFault as host_config_fault:
                    self.module.fail_json(
                        msg=
                        "Failed to update vmk due to host config issues : %s" %
                        to_native(host_config_fault.msg))
                except vim.fault.InvalidState as invalid_state:
                    self.module.fail_json(
                        msg=
                        "Failed to update vmk as ipv6 address is specified in an ipv4 only system : %s"
                        % to_native(invalid_state.msg))
                except vmodl.fault.InvalidArgument as invalid_arg:
                    self.module.fail_json(
                        msg=
                        "Failed to update vmk as IP address or Subnet Mask in the IP configuration"
                        "are invalid or PortGroup does not exist : %s" %
                        to_native(invalid_arg.msg))

            if changed_services:
                changed_list.append("Services")
                services_previous = []
                vnic_manager = self.esxi_host_obj.configManager.virtualNicManager

                if changed_service_mgmt:
                    if self.vnic.device in service_type_vmks['management']:
                        services_previous.append('Mgmt')
                    operation = 'select' if self.enable_mgmt else 'deselect'
                    self.set_service_type(vnic_manager=vnic_manager,
                                          vmk=self.vnic,
                                          service_type='management',
                                          operation=operation)

                if changed_service_vmotion:
                    if self.vnic.device in service_type_vmks['vmotion']:
                        services_previous.append('vMotion')
                    operation = 'select' if self.enable_vmotion else 'deselect'
                    self.set_service_type(vnic_manager=vnic_manager,
                                          vmk=self.vnic,
                                          service_type='vmotion',
                                          operation=operation)

                if changed_service_ft:
                    if self.vnic.device in service_type_vmks[
                            'faultToleranceLogging']:
                        services_previous.append('FT')
                    operation = 'select' if self.enable_ft else 'deselect'
                    self.set_service_type(vnic_manager=vnic_manager,
                                          vmk=self.vnic,
                                          service_type='faultToleranceLogging',
                                          operation=operation)

                if changed_service_prov:
                    if self.vnic.device in service_type_vmks[
                            'vSphereProvisioning']:
                        services_previous.append('Prov')
                    operation = 'select' if self.enable_provisioning else 'deselect'
                    self.set_service_type(vnic_manager=vnic_manager,
                                          vmk=self.vnic,
                                          service_type='vSphereProvisioning',
                                          operation=operation)

                if changed_service_rep:
                    if self.vnic.device in service_type_vmks[
                            'vSphereReplication']:
                        services_previous.append('Repl')
                    operation = 'select' if self.enable_replication else 'deselect'
                    self.set_service_type(vnic_manager=vnic_manager,
                                          vmk=self.vnic,
                                          service_type='vSphereReplication',
                                          operation=operation)

                if changed_service_rep_nfc:
                    if self.vnic.device in service_type_vmks[
                            'vSphereReplicationNFC']:
                        services_previous.append('Repl_NFC')
                    operation = 'select' if self.enable_replication_nfc else 'deselect'
                    self.set_service_type(vnic_manager=vnic_manager,
                                          vmk=self.vnic,
                                          service_type='vSphereReplicationNFC',
                                          operation=operation)

                if changed_service_vsan:
                    if self.vnic.device in service_type_vmks['vsan']:
                        services_previous.append('VSAN')
                    if self.enable_vsan:
                        results['vsan'] = self.set_vsan_service_type()
                    else:
                        self.set_service_type(vnic_manager=vnic_manager,
                                              vmk=self.vnic,
                                              service_type='vsan',
                                              operation=operation)

                results['services_previous'] = ', '.join(services_previous)
        else:
            message = "VMkernel Adapter already configured properly"

        results['changed'] = changed
        results['msg'] = message
        results['device'] = self.vnic.device
        self.module.exit_json(**results)
Esempio n. 14
0
    def __init__(self, module):
        super(PyVmomiHelper, self).__init__(module)
        if self.params['network']:
            self.network_type = self.params['network'].get('type')
            self.ip_address = self.params['network'].get('ip_address', None)
            self.subnet_mask = self.params['network'].get('subnet_mask', None)
            self.default_gateway = self.params['network'].get(
                'default_gateway', None)
            self.tcpip_stack = self.params['network'].get('tcpip_stack')
        self.device = self.params['device']
        if self.network_type == 'dhcp' and not self.device:
            module.fail_json(
                msg=
                "device is a required parameter when network type is set to 'dhcp'"
            )
        self.mtu = self.params['mtu']
        self.enable_vsan = self.params['enable_vsan']
        self.enable_vmotion = self.params['enable_vmotion']
        self.enable_mgmt = self.params['enable_mgmt']
        self.enable_ft = self.params['enable_ft']
        self.enable_provisioning = self.params['enable_provisioning']
        self.enable_replication = self.params['enable_replication']
        self.enable_replication_nfc = self.params['enable_replication_nfc']

        self.vswitch_name = self.params['vswitch_name']
        self.vds_name = self.params['dvswitch_name']
        self.port_group_name = self.params['portgroup_name']

        self.esxi_host_name = self.params['esxi_hostname']
        hosts = self.get_all_host_objs(esxi_host_name=self.esxi_host_name)
        if hosts:
            self.esxi_host_obj = hosts[0]
        else:
            self.module.fail_json(
                msg=
                "Failed to get details of ESXi server. Please specify esxi_hostname."
            )

        if self.network_type == 'static':
            if self.module.params['state'] == 'absent':
                pass
            elif not self.ip_address:
                module.fail_json(
                    msg=
                    "ip_address is a required parameter when network type is set to 'static'"
                )
            elif not self.subnet_mask:
                module.fail_json(
                    msg=
                    "subnet_mask is a required parameter when network type is set to 'static'"
                )

        # find Port Group
        if self.vswitch_name:
            self.port_group_obj = self.get_port_group_by_name(
                host_system=self.esxi_host_obj,
                portgroup_name=self.port_group_name,
                vswitch_name=self.vswitch_name)
            if not self.port_group_obj:
                module.fail_json(msg="Portgroup '%s' not found on vSS '%s'" %
                                 (self.port_group_name, self.vswitch_name))
        elif self.vds_name:
            self.dv_switch_obj = find_dvs_by_name(self.content, self.vds_name)
            if not self.dv_switch_obj:
                module.fail_json(msg="vDS '%s' not found" % self.vds_name)
            self.port_group_obj = find_dvspg_by_name(self.dv_switch_obj,
                                                     self.port_group_name)
            if not self.port_group_obj:
                module.fail_json(msg="Portgroup '%s' not found on vDS '%s'" %
                                 (self.port_group_name, self.vds_name))

        # find VMkernel Adapter
        if self.device:
            self.vnic = self.get_vmkernel_by_device(device_name=self.device)
        else:
            # config change (e.g. DHCP to static, or vice versa); doesn't work with virtual port change
            self.vnic = self.get_vmkernel_by_portgroup_new(
                port_group_name=self.port_group_name)
            if not self.vnic and self.network_type == 'static':
                # vDS to vSS or vSS to vSS (static IP)
                self.vnic = self.get_vmkernel_by_ip(ip_address=self.ip_address)
Esempio n. 15
0
    def check_dvspg_state(self):
        self.dv_switch = find_dvs_by_name(self.content,
                                          self.module.params['switch_name'])

        if self.dv_switch is None:
            self.module.fail_json(
                msg="A distributed virtual switch with name %s does not exist"
                % self.module.params['switch_name'])
        self.dvs_portgroup = find_dvspg_by_name(
            self.dv_switch, self.module.params['portgroup_name'])

        if self.dvs_portgroup is None:
            return 'absent'

        # Check config
        # Basic config
        if self.dvs_portgroup.config.numPorts != self.module.params[
                'num_ports']:
            return 'update'

        # Default port config
        defaultPortConfig = self.dvs_portgroup.config.defaultPortConfig
        if self.module.params['vlan_trunk']:
            if not isinstance(
                    defaultPortConfig.vlan,
                    vim.dvs.VmwareDistributedVirtualSwitch.TrunkVlanSpec):
                return 'update'
            if map(lambda x: (x.start, x.end),
                   defaultPortConfig.vlan.vlanId) != self.create_vlan_list():
                return 'update'
        else:
            if not isinstance(
                    defaultPortConfig.vlan,
                    vim.dvs.VmwareDistributedVirtualSwitch.VlanIdSpec):
                return 'update'
            if defaultPortConfig.vlan.vlanId != int(
                    self.module.params['vlan_id']):
                return 'update'

        if defaultPortConfig.securityPolicy.allowPromiscuous.value != self.module.params['network_policy']['promiscuous'] or \
                defaultPortConfig.securityPolicy.forgedTransmits.value != self.module.params['network_policy']['forged_transmits'] or \
                defaultPortConfig.securityPolicy.macChanges.value != self.module.params['network_policy']['mac_changes']:
            return 'update'

        # Teaming Policy
        teamingPolicy = self.dvs_portgroup.config.defaultPortConfig.uplinkTeamingPolicy
        if teamingPolicy.policy.value != self.module.params['teaming_policy']['load_balance_policy'] or \
                teamingPolicy.reversePolicy.value != self.module.params['teaming_policy']['inbound_policy'] or \
                teamingPolicy.notifySwitches.value != self.module.params['teaming_policy']['notify_switches'] or \
                teamingPolicy.rollingOrder.value != self.module.params['teaming_policy']['rolling_order']:
            return 'update'

        # PG policy (advanced_policy)
        policy = self.dvs_portgroup.config.policy
        if policy.blockOverrideAllowed != self.module.params['port_policy']['block_override'] or \
                policy.ipfixOverrideAllowed != self.module.params['port_policy']['ipfix_override'] or \
                policy.livePortMovingAllowed != self.module.params['port_policy']['live_port_move'] or \
                policy.networkResourcePoolOverrideAllowed != self.module.params['port_policy']['network_rp_override'] or \
                policy.portConfigResetAtDisconnect != self.module.params['port_policy']['port_config_reset_at_disconnect'] or \
                policy.securityPolicyOverrideAllowed != self.module.params['port_policy']['security_override'] or \
                policy.shapingOverrideAllowed != self.module.params['port_policy']['shaping_override'] or \
                policy.trafficFilterOverrideAllowed != self.module.params['port_policy']['traffic_filter_override'] or \
                policy.uplinkTeamingOverrideAllowed != self.module.params['port_policy']['uplink_teaming_override'] or \
                policy.vendorConfigOverrideAllowed != self.module.params['port_policy']['vendor_config_override'] or \
                policy.vlanOverrideAllowed != self.module.params['port_policy']['vlan_override']:
            return 'update'

        # PG Type
        if self.dvs_portgroup.config.type != self.module.params[
                'portgroup_type']:
            return 'update'

        return 'present'
Esempio n. 16
0
    def create_dvswitch(self):
        """Create a DVS"""
        changed = True
        results = dict(changed=changed)

        spec = vim.DistributedVirtualSwitch.CreateSpec()
        spec.configSpec = vim.dvs.VmwareDistributedVirtualSwitch.ConfigSpec()
        # Name
        results['dvswitch'] = self.switch_name
        spec.configSpec.name = self.switch_name
        # MTU
        results['mtu'] = self.mtu
        spec.configSpec.maxMtu = self.mtu
        # Discovery Protocol type and operation
        results['discovery_protocol'] = self.discovery_protocol
        results['discovery_operation'] = self.discovery_operation
        spec.configSpec.linkDiscoveryProtocolConfig = self.create_ldp_spec()
        # Administrator contact
        results['contact'] = self.contact_name
        results['contact_details'] = self.contact_details
        if self.contact_name or self.contact_details:
            spec.contact = self.create_contact_spec()
        # Description
        results['description'] = self.description
        if self.description:
            spec.description = self.description
        # Uplinks
        results['uplink_quantity'] = self.uplink_quantity
        spec.configSpec.uplinkPortPolicy = vim.DistributedVirtualSwitch.NameArrayUplinkPortPolicy(
        )
        for count in range(1, self.uplink_quantity + 1):
            spec.configSpec.uplinkPortPolicy.uplinkPortName.append(
                "%s%d" % (self.uplink_prefix, count))
        results['uplinks'] = spec.configSpec.uplinkPortPolicy.uplinkPortName
        # Version
        results['version'] = self.switch_version
        if self.switch_version:
            spec.productInfo = self.create_product_spec(self.switch_version)

        if self.module.check_mode:
            result = "DVS would be created"
        else:
            # Create DVS
            network_folder = self.folder_obj
            task = network_folder.CreateDVS_Task(spec)
            try:
                wait_for_task(task)
            except TaskError as invalid_argument:
                self.module.fail_json(msg="Failed to create DVS : %s" %
                                      to_native(invalid_argument))
            # Find new DVS
            self.dvs = find_dvs_by_name(self.content, self.switch_name)
            changed_multicast = False
            spec = vim.dvs.VmwareDistributedVirtualSwitch.ConfigSpec()
            # Use the same version in the new spec; The version will be increased by one by the API automatically
            spec.configVersion = self.dvs.config.configVersion
            # Set multicast filtering mode
            results['multicast_filtering_mode'] = self.multicast_filtering_mode
            multicast_filtering_mode = self.get_api_mc_filtering_mode(
                self.multicast_filtering_mode)
            if self.dvs.config.multicastFilteringMode != multicast_filtering_mode:
                changed_multicast = True
                spec.multicastFilteringMode = multicast_filtering_mode
            spec.multicastFilteringMode = self.get_api_mc_filtering_mode(
                self.multicast_filtering_mode)
            if changed_multicast:
                self.update_dvs_config(self.dvs, spec)
            # Set Health Check config
            results['health_check_vlan'] = self.health_check_vlan
            results['health_check_teaming'] = self.health_check_teaming
            result = self.check_health_check_config(
                self.dvs.config.healthCheckConfig)
            changed_health_check = result[1]
            if changed_health_check:
                self.update_health_check_config(self.dvs, result[0])
            result = "DVS created"
        self.module.exit_json(changed=changed, result=to_native(result))