Exemplo n.º 1
0
    def create_network_interface(
        self,
        location,
        resource_group_name,
        interface_name,
        config_name,
        subnet_id,
        public_ip_id=None,
        security_group_id=None,
    ):
        ip_configuration = NetworkInterfaceIPConfiguration(
            name=config_name, subnet={'id': subnet_id})

        if public_ip_id:
            ip_configuration.public_ip_address = {'id': public_ip_id}

        interface_parameters = NetworkInterface(
            location=location,
            ip_configurations=[ip_configuration],
        )

        if security_group_id:
            interface_parameters.network_security_group = {
                'id': security_group_id
            }

        try:
            return self.network_client.network_interfaces.create_or_update(
                resource_group_name, interface_name, interface_parameters)
        except ClientException as exc:
            raise AzureBackendError(exc)
Exemplo n.º 2
0
  def create_network_interface(self, network_client, interface_name, ip_name,
                               subnet, parameters):
    """ Creates the Public IP Address resource and uses that to create the
    Network Interface.
    Args:
      network_client: A NetworkManagementClient instance.
      interface_name: The name to use for the Network Interface resource.
      ip_name: The name to use for the Public IP Address resource.
      subnet: The Subnet resource from the Virtual Network created.
      parameters:  A dict, containing all the parameters necessary to
        authenticate this user with Azure.
    """
    group_name = parameters[self.PARAM_RESOURCE_GROUP]
    region = parameters[self.PARAM_ZONE]
    utils.log("Creating/Updating the Public IP Address '{}'".format(ip_name))
    ip_address = PublicIPAddress(
      location=region, public_ip_allocation_method=IPAllocationMethod.dynamic,
      idle_timeout_in_minutes=4)
    result = network_client.public_ip_addresses.create_or_update(
      group_name, ip_name, ip_address)
    self.sleep_until_update_operation_done(result, ip_name)
    public_ip_address = network_client.public_ip_addresses.get(group_name, ip_name)

    utils.log("Creating/Updating the Network Interface '{}'".format(interface_name))
    network_interface_ip_conf = NetworkInterfaceIPConfiguration(
      name=interface_name, private_ip_allocation_method=IPAllocationMethod.dynamic,
      subnet=subnet, public_ip_address=PublicIPAddress(id=(public_ip_address.id)))

    result = network_client.network_interfaces.create_or_update(
      group_name, interface_name, NetworkInterface(location=region,
        ip_configurations=[network_interface_ip_conf]))
    self.sleep_until_update_operation_done(result, interface_name)
 def get(self, resource_group_name: str, network_interface_name: str) -> NetworkInterface:
     try:
         with open(self.path / resource_group_name / f"nic-{network_interface_name}.json", "r",
                   encoding="utf-8") as file:
             return NetworkInterface.deserialize(json.load(file))
     except FileNotFoundError:
         raise ResourceNotFoundError("NIC not found") from None
 def list(self, resource_group_name: str) -> List[NetworkInterface]:
     try:
         files = [file for file in os.listdir(self.path / resource_group_name) if file.startswith("nic-")]
     except FileNotFoundError:
         raise ResourceNotFoundError("No resource group") from None
     elements = []
     for file in files:
         with open(self.path / resource_group_name / file, "r", encoding="utf-8") as file:
             elements.append(NetworkInterface.deserialize(json.load(file)))
     return elements
Exemplo n.º 5
0
def associate_nic(name: str, nic: NetworkInterface) -> Union[None, Error]:
    resource_group = get_base_resource_group()
    nsg = get_nsg(name)
    if not nsg:
        return Error(
            code=ErrorCode.UNABLE_TO_FIND,
            errors=["cannot associate nic. nsg %s not found" % name],
        )

    if nsg.location != nic.location:
        return Error(
            code=ErrorCode.UNABLE_TO_UPDATE,
            errors=[
                "network interface and nsg have to be in the same region.",
                "nsg %s %s, nic: %s %s" %
                (nsg.name, nsg.location, nic.name, nic.location),
            ],
        )

    if nic.network_security_group and nic.network_security_group.id == nsg.id:
        logging.info("NIC %s and NSG %s already associated, not updating",
                     nic.name, name)
        return None

    logging.info("associating nic %s with nsg: %s %s", nic.name,
                 resource_group, name)

    nic.network_security_group = nsg
    network_client = get_network_client()
    try:
        network_client.network_interfaces.begin_create_or_update(
            resource_group, nic.name, nic)
    except (ResourceNotFoundError, CloudError) as err:
        if is_concurrent_request_error(str(err)):
            logging.debug(
                "associate NSG with NIC had conflicts",
                "with concurrent request, ignoring %s",
                err,
            )
            return None
        return Error(
            code=ErrorCode.UNABLE_TO_UPDATE,
            errors=[
                "Unable to associate nsg %s with nic %s due to %s" % (
                    name,
                    nic.name,
                    err,
                )
            ],
        )

    return None
Exemplo n.º 6
0
def dissociate_nic(name: str, nic: NetworkInterface) -> Union[None, Error]:
    if nic.network_security_group is None:
        return None
    resource_group = get_base_resource_group()
    nsg = get_nsg(name)
    if not nsg:
        return Error(
            code=ErrorCode.UNABLE_TO_FIND,
            errors=["cannot update nsg rules. nsg %s not found" % name],
        )
    if nsg.id != nic.network_security_group.id:
        return Error(
            code=ErrorCode.UNABLE_TO_UPDATE,
            errors=[
                "network interface is not associated with this nsg.",
                "nsg %s, nic: %s, nic.nsg: %s" % (
                    nsg.id,
                    nic.name,
                    nic.network_security_group.id,
                ),
            ],
        )

    logging.info("dissociating nic %s with nsg: %s %s", nic.name,
                 resource_group, name)

    nic.network_security_group = None
    network_client = get_network_client()
    try:
        network_client.network_interfaces.begin_create_or_update(
            resource_group, nic.name, nic)
    except (ResourceNotFoundError, CloudError) as err:
        if is_concurrent_request_error(str(err)):
            logging.debug(
                "dissociate nsg with nic had conflicts with ",
                "concurrent request, ignoring %s",
                err,
            )
            return None
        return Error(
            code=ErrorCode.UNABLE_TO_UPDATE,
            errors=[
                "Unable to dissociate nsg %s with nic %s due to %s" % (
                    name,
                    nic.name,
                    err,
                )
            ],
        )

    return None
    def create_network_interface(
        self,
        interface_name,
        resource_group_name,
        region,
        subnet,
        private_ip_allocation_method,
        enable_ip_forwarding,
        network_security_group,
        tags,
        public_ip_address=None,
        private_ip_address=None,
    ):
        """Create VM Network interface.

        :param str interface_name:
        :param str resource_group_name:
        :param public_ip_address:
        :param str region:
        :param subnet:
        :param private_ip_allocation_method:
        :param bool enable_ip_forwarding:
        :param network_security_group:
        :param dict[str, str] tags:
        :param str private_ip_address:
        :return:
        """
        ip_config = NetworkInterfaceIPConfiguration(
            name=self.NETWORK_INTERFACE_IP_CONFIG_NAME,
            private_ip_allocation_method=private_ip_allocation_method,
            subnet=subnet,
            private_ip_address=private_ip_address,
            public_ip_address=public_ip_address,
        )

        network_interface = NetworkInterface(
            location=region,
            network_security_group=network_security_group,
            ip_configurations=[ip_config],
            enable_ip_forwarding=enable_ip_forwarding,
            tags=tags,
        )

        operation_poller = self._network_client.network_interfaces.create_or_update(
            resource_group_name=resource_group_name,
            network_interface_name=interface_name,
            parameters=network_interface,
        )

        return operation_poller.result()
Exemplo n.º 8
0
 def get_nic_params(self, controller_ip):
     location = self.configuration.get('location')
     vm_name = self.vm_json.get('name')
     try:
         return NetworkInterface(
             location=location,
             ip_configurations=[
                 NetworkInterfaceIPConfiguration(
                     name='%s-%s' % (vm_name, controller_ip),
                     private_ip_address=controller_ip,
                     private_ip_allocation_method='Static',
                     private_ip_address_version='IPv4',
                     subnet=Subnet(id=self.subnet_id))
             ])
     except Exception as e:
         fail('Error while getting nic parameters %s' % str(e))
Exemplo n.º 9
0
    def create_nic(self, interface_name, group_name, management_group_name,
                   network_client, public_ip_address, region, subnet,
                   private_ip_allocation_method, tags, virtual_network_name,
                   logger):
        """
        The method creates or updates network interface.
        Parameter
        :param logger:
        :param virtual_network_name:
        :param group_name:
        :param interface_name:
        :param management_group_name:
        :param network_client:
        :param public_ip_address:
        :param region:
        :param subnet:
        :param IPAllocationMethod private_ip_allocation_method:
        :param tags:
        :return:
        """

        # private_ip_address in required only in the case of static allocation method
        # in the case of dynamic allocation method is ignored
        private_ip_address = ""
        if private_ip_allocation_method == IPAllocationMethod.static:
            private_ip_address = self.ip_service.get_available_private_ip(
                network_client, management_group_name, virtual_network_name,
                subnet.address_prefix[:-3], logger)

        operation_poller = network_client.network_interfaces.create_or_update(
            group_name,
            interface_name,
            NetworkInterface(location=region,
                             ip_configurations=[
                                 NetworkInterfaceIPConfiguration(
                                     name='default',
                                     private_ip_allocation_method=
                                     private_ip_allocation_method,
                                     subnet=subnet,
                                     private_ip_address=private_ip_address,
                                     public_ip_address=public_ip_address,
                                 ),
                             ],
                             tags=tags),
        )

        return operation_poller.result()
    def exec_module(self, **kwargs):

        for key in self.module_arg_spec.keys() + ["tags"]:
            setattr(self, key, kwargs[key])

        results = dict()
        changed = False
        nic = None
        subnet = None
        nsg = None
        pip = None

        resource_group = self.get_resource_group(self.resource_group)
        if not self.location:
            # Set default location
            self.location = resource_group.location

        if self.state == "present":
            if self.virtual_network_name and not self.subnet_name:
                self.fail("Parameter error: a subnet is required when passing a virtual_network_name.")

            if self.subnet_name and not self.virtual_network_name:
                self.fail("Parameter error: virtual_network_name is required when passing a subnet value.")

            if self.virtual_network_name and self.subnet_name:
                subnet = self.get_subnet(self.virtual_network_name, self.subnet_name)

            if self.public_ip_address_name:
                pip = self.get_public_ip_address(self.public_ip_address_name)

            if self.security_group_name:
                nsg = self.get_security_group(self.security_group_name)

        try:
            self.log("Fetching network interface {0}".format(self.name))
            nic = self.network_client.network_interfaces.get(self.resource_group, self.name)

            self.log("Network interface {0} exists".format(self.name))
            self.check_provisioning_state(nic, self.state)
            results = nic_to_dict(nic)
            self.log(results, pretty_print=True)

            if self.state == "present":

                update_tags, results["tags"] = self.update_tags(results["tags"])
                if update_tags:
                    changed = True

                if self.private_ip_address:
                    if results["ip_configuration"]["private_ip_address"] != self.private_ip_address:
                        self.log("CHANGED: network interface {0} private ip".format(self.name))
                        changed = True
                        results["ip_configuration"]["private_ip_address"] = self.private_ip_address

                if self.public_ip_address_name:
                    if results["ip_configuration"]["public_ip_address"].get("id") != pip.id:
                        self.log("CHANGED: network interface {0} public ip".format(self.name))
                        changed = True
                        results["ip_configuration"]["public_ip_address"]["id"] = pip.id
                        results["ip_configuration"]["public_ip_address"]["name"] = pip.name

                if self.security_group_name:
                    if results["network_security_group"].get("id") != nsg.id:
                        self.log("CHANGED: network interface {0} network security group".format(self.name))
                        changed = True
                        results["network_security_group"]["id"] = nsg.id
                        results["network_security_group"]["name"] = nsg.name

                if self.private_ip_allocation_method:
                    if results["ip_configuration"]["private_ip_allocation_method"] != self.private_ip_allocation_method:
                        self.log("CHANGED: network interface {0} private ip allocation".format(self.name))
                        changed = True
                        results["ip_configuration"]["private_ip_allocation_method"] = self.private_ip_allocation_method
                        if self.private_ip_allocation_method == "Dynamic":
                            results["ip_configuration"]["private_ip_address"] = None

                if self.subnet_name:
                    if results["ip_configuration"]["subnet"].get("id") != subnet.id:
                        changed = True
                        self.log("CHANGED: network interface {0} subnet".format(self.name))
                        results["ip_configuration"]["subnet"]["id"] = subnet.id
                        results["ip_configuration"]["subnet"]["name"] = subnet.name
                        results["ip_configuration"]["subnet"]["virtual_network_name"] = self.virtual_network_name

            elif self.state == "absent":
                self.log("CHANGED: network interface {0} exists but requested state is 'absent'".format(self.name))
                changed = True
        except CloudError:
            self.log("Network interface {0} does not exist".format(self.name))
            if self.state == "present":
                self.log(
                    "CHANGED: network interface {0} does not exist but requested state is "
                    "'present'".format(self.name)
                )
                changed = True

        self.results["changed"] = changed
        self.results["state"] = results

        if self.check_mode:
            return self.results

        if changed:
            if self.state == "present":
                if not nic:
                    # create network interface
                    self.log("Creating network interface {0}.".format(self.name))

                    # check required parameters
                    if not self.subnet_name:
                        self.fail("parameter error: subnet_name required when creating a network interface.")
                    if not self.virtual_network_name:
                        self.fail("parameter error: virtual_network_name required when creating a network interface.")

                    if not self.security_group_name:
                        # create default security group
                        nsg = self.create_default_securitygroup(
                            self.resource_group, self.location, self.name, self.os_type, self.open_ports
                        )

                    if not pip and self.public_ip:
                        # create a default public_ip
                        pip = self.create_default_pip(
                            self.resource_group, self.location, self.name, self.public_ip_allocation_method
                        )

                    nic = NetworkInterface(
                        location=self.location,
                        tags=self.tags,
                        ip_configurations=[
                            NetworkInterfaceIPConfiguration(
                                private_ip_allocation_method=self.private_ip_allocation_method
                            )
                        ],
                    )
                    # nic.name = self.name
                    nic.ip_configurations[0].subnet = Subnet(id=subnet.id)
                    nic.ip_configurations[0].name = "default"
                    nic.network_security_group = NetworkSecurityGroup(
                        id=nsg.id, location=nsg.location, resource_guid=nsg.resource_guid
                    )
                    if self.private_ip_address:
                        nic.ip_configurations[0].private_ip_address = self.private_ip_address

                    if pip:
                        nic.ip_configurations[0].public_ip_address = PublicIPAddress(
                            id=pip.id, location=pip.location, resource_guid=pip.resource_guid
                        )
                else:
                    self.log("Updating network interface {0}.".format(self.name))
                    nic = NetworkInterface(
                        id=results["id"],
                        location=results["location"],
                        tags=results["tags"],
                        ip_configurations=[
                            NetworkInterfaceIPConfiguration(
                                private_ip_allocation_method=results["ip_configuration"]["private_ip_allocation_method"]
                            )
                        ],
                    )
                    subnet = self.get_subnet(
                        results["ip_configuration"]["subnet"]["virtual_network_name"],
                        results["ip_configuration"]["subnet"]["name"],
                    )
                    nic.ip_configurations[0].subnet = Subnet(id=subnet.id)
                    nic.ip_configurations[0].name = results["ip_configuration"]["name"]
                    # nic.name = name=results['name'],

                    if results["ip_configuration"].get("private_ip_address"):
                        nic.ip_configurations[0].private_ip_address = results["ip_configuration"]["private_ip_address"]

                    if results["ip_configuration"]["public_ip_address"].get("id"):
                        pip = self.get_public_ip_address(results["ip_configuration"]["public_ip_address"]["name"])
                        nic.ip_configurations[0].public_ip_address = PublicIPAddress(
                            id=pip.id, location=pip.location, resource_guid=pip.resource_guid
                        )
                    # name=pip.name,

                    if results["network_security_group"].get("id"):
                        nsg = self.get_security_group(results["network_security_group"]["name"])
                        nic.network_security_group = NetworkSecurityGroup(
                            id=nsg.id, location=nsg.location, resource_guid=nsg.resource_guid
                        )

                # See what actually gets sent to the API
                request = self.serialize_obj(nic, "NetworkInterface")
                self.log(request, pretty_print=True)

                self.results["state"] = self.create_or_update_nic(nic)

            elif self.state == "absent":
                self.log("Deleting network interface {0}".format(self.name))
                self.delete_nic()

        return self.results
Exemplo n.º 11
0
    def test_remediate_success(self):
        compute_client = Mock()
        nw_profile = NetworkProfile(network_interfaces=[
            NetworkInterfaceReference(
                id=
                "/subscriptions/subscription_id/resourceGroups/resource_group/providers/Microsoft.Network"
                "/networkInterfaces/vm_nameVMNic ")
        ])

        compute_client.virtual_machines.get.return_value = VirtualMachine(
            id=
            "/subscriptions/subscription_id/resourceGroups/resource_group/providers/Microsoft.Compute"
            "/virtualMachines/vm_name",
            location="eastus",
            network_profile=nw_profile,
        )
        nw_client = Mock()
        nw_client.network_interfaces.get.return_value = NetworkInterface(
            id=
            "/subscriptions/subscription_id/resourceGroups/resource_group/providers/Microsoft.Network"
            "/networkInterfaces/vm_nameVMNic",
            network_security_group=NetworkSecurityGroup(
                id=
                "/subscriptions/subscription_id/resourceGroups/resource_name/providers/Microsoft.Network"
                "/networkSecurityGroups/vm_nameNSG "),
        )

        nw_client.network_security_groups.get.return_value = NetworkSecurityGroup(
            id=
            "/subscriptions/subscription_id/resourceGroups/resource_name/providers/Microsoft.Network"
            "/networkSecurityGroups/vm_nameNSG",
            security_rules=[
                SecurityRule(
                    protocol="All",
                    access="Allow",
                    direction="Inbound",
                    source_address_prefix="*",
                    destination_port_ranges=["22", "3389"],
                ),
                SecurityRule(
                    protocol="All",
                    access="Allow",
                    direction="Inbound",
                    source_address_prefix="*",
                    destination_port_ranges=["20-30", "3389"],
                ),
                SecurityRule(
                    protocol="All",
                    access="Allow",
                    direction="Inbound",
                    source_address_prefix="*",
                    destination_port_range="22",
                ),
            ],
        )

        action = VMSecurityGroupClosePort22()
        assert (action.remediate(compute_client, nw_client, "resource_name",
                                 "vm_name") == 0)
        assert nw_client.network_security_groups.create_or_update.call_count == 1
        call_args = nw_client.network_security_groups.create_or_update.call_args
        updated_sg = call_args.args[2]
        security_rules = updated_sg.security_rules
        assert len(security_rules) == 2
        assert security_rules[0].destination_port_ranges == ["3389"]
        assert security_rules[1].destination_port_ranges == [
            "20-21", "23-30", "3389"
        ]
Exemplo n.º 12
0
def create_interface(call=None, kwargs=None):  # pylint: disable=unused-argument
    '''
    Create a network interface
    '''
    global netconn  # pylint: disable=global-statement,invalid-name
    if not netconn:
        netconn = get_conn(NetworkManagementClient,
                           NetworkManagementClientConfiguration)

    if kwargs is None:
        kwargs = {}
    vm_ = kwargs

    if kwargs.get('location') is None:
        kwargs['location'] = get_location()

    if kwargs.get('resource_group') is None:
        kwargs['resource_group'] = config.get_cloud_config_value(
            'resource_group', vm_, __opts__, search_global=True)

    if kwargs.get('network') is None:
        kwargs['network'] = config.get_cloud_config_value('network',
                                                          vm_,
                                                          __opts__,
                                                          search_global=True)

    if kwargs.get('subnet') is None:
        kwargs['subnet'] = config.get_cloud_config_value('subnet',
                                                         vm_,
                                                         __opts__,
                                                         default='default',
                                                         search_global=True)

    if kwargs.get('iface_name') is None:
        kwargs['iface_name'] = '{0}-iface0'.format(vm_['name'])

    if 'network_resource_group' in kwargs:
        group = kwargs['network_resource_group']
    else:
        group = kwargs['resource_group']

    subnet_obj = netconn.subnets.get(
        resource_group_name=kwargs['resource_group'],
        virtual_network_name=kwargs['network'],
        subnet_name=kwargs['subnet'],
    )

    ip_kwargs = {}
    if bool(kwargs.get('public_ip', False)) is True:
        pub_ip_name = '{0}-ip'.format(kwargs['iface_name'])
        poller = netconn.public_ip_addresses.create_or_update(
            resource_group_name=kwargs['resource_group'],
            public_ip_address_name=pub_ip_name,
            parameters=PublicIPAddress(
                location=kwargs['location'],
                public_ip_allocation_method=IPAllocationMethod.static,
            ),
        )
        count = 0
        poller.wait()
        while True:
            try:
                pub_ip_data = netconn.public_ip_addresses.get(
                    kwargs['resource_group'],
                    pub_ip_name,
                )
                if pub_ip_data.ip_address:  # pylint: disable=no-member
                    ip_kwargs['public_ip_address'] = Resource(
                        str(pub_ip_data.id),  # pylint: disable=no-member
                    )
                    break
            except CloudError:
                pass
            count += 1
            if count > 120:
                raise ValueError('Timed out waiting for public IP Address.')
            time.sleep(5)

    iface_params = NetworkInterface(
        name=kwargs['iface_name'],
        location=kwargs['location'],
        ip_configurations=[
            NetworkInterfaceIPConfiguration(
                name='{0}-ip'.format(kwargs['iface_name']),
                private_ip_allocation_method='Dynamic',
                subnet=subnet_obj,
                **ip_kwargs)
        ])

    netconn.network_interfaces.create_or_update(kwargs['resource_group'],
                                                kwargs['iface_name'],
                                                iface_params)
    count = 0
    while True:
        try:
            return show_interface(kwargs=kwargs)
        except CloudError:
            count += 1
            if count > 120:
                raise ValueError(
                    'Timed out waiting for operation to complete.')
            time.sleep(5)
    def exec_module(self, **kwargs):

        for key in self.module_arg_spec.keys() + ['tags']:
            setattr(self, key, kwargs[key])

        results = dict()
        changed = False
        nic = None
        subnet = None
        nsg = None
        pip = None

        resource_group = self.get_resource_group(self.resource_group)
        if not self.location:
            # Set default location
            self.location = resource_group.location

        if not NAME_PATTERN.match(self.name):
            self.fail(
                "Parameter error: name must begin with a letter or number, end with a letter or number "
                "and contain at least one number.")

        if self.state == 'present':
            if self.virtual_network_name and not self.subnet_name:
                self.fail(
                    "Parameter error: a subnet is required when passing a virtual_network_name."
                )

            if self.subnet_name and not self.virtual_network_name:
                self.fail(
                    "Parameter error: virtual_network_name is required when passing a subnet value."
                )

            if self.virtual_network_name and self.subnet_name:
                subnet = self.get_subnet(self.virtual_network_name,
                                         self.subnet_name)

            if self.public_ip_address_name:
                pip = self.get_public_ip_address(self.public_ip_address_name)

            if self.security_group_name:
                nsg = self.get_security_group(self.security_group_name)

        try:
            self.log('Fetching network interface {0}'.format(self.name))
            nic = self.network_client.network_interfaces.get(
                self.resource_group, self.name)

            self.log('Network interface {0} exists'.format(self.name))
            self.check_provisioning_state(nic, self.state)
            results = nic_to_dict(nic)
            self.log(results, pretty_print=True)

            if self.state == 'present':

                update_tags, results['tags'] = self.update_tags(
                    results['tags'])
                if update_tags:
                    changed = True

                if self.private_ip_address:
                    if results['ip_configuration'][
                            'private_ip_address'] != self.private_ip_address:
                        self.log(
                            "CHANGED: network interface {0} private ip".format(
                                self.name))
                        changed = True
                        results['ip_configuration'][
                            'private_ip_address'] = self.private_ip_address

                if self.public_ip_address_name:
                    if results['ip_configuration']['public_ip_address'].get(
                            'id') != pip.id:
                        self.log(
                            "CHANGED: network interface {0} public ip".format(
                                self.name))
                        changed = True
                        results['ip_configuration']['public_ip_address'][
                            'id'] = pip.id
                        results['ip_configuration']['public_ip_address'][
                            'name'] = pip.name

                if self.security_group_name:
                    if results['network_security_group'].get('id') != nsg.id:
                        self.log(
                            "CHANGED: network interface {0} network security group"
                            .format(self.name))
                        changed = True
                        results['network_security_group']['id'] = nsg.id
                        results['network_security_group']['name'] = nsg.name

                if self.private_ip_allocation_method:
                    if results['ip_configuration'][
                            'private_ip_allocation_method'] != self.private_ip_allocation_method:
                        self.log(
                            "CHANGED: network interface {0} private ip allocation"
                            .format(self.name))
                        changed = True
                        results['ip_configuration'][
                            'private_ip_allocation_method'] = self.private_ip_allocation_method
                        if self.private_ip_allocation_method == 'Dynamic':
                            results['ip_configuration'][
                                'private_ip_address'] = None

                if self.subnet_name:
                    if results['ip_configuration']['subnet'].get(
                            'id') != subnet.id:
                        changed = True
                        self.log(
                            "CHANGED: network interface {0} subnet".format(
                                self.name))
                        results['ip_configuration']['subnet']['id'] = subnet.id
                        results['ip_configuration']['subnet'][
                            'name'] = subnet.name
                        results['ip_configuration']['subnet'][
                            'virtual_network_name'] = self.virtual_network_name

            elif self.state == 'absent':
                self.log(
                    "CHANGED: network interface {0} exists but requested state is 'absent'"
                    .format(self.name))
                changed = True
        except CloudError:
            self.log('Network interface {0} does not exist'.format(self.name))
            if self.state == 'present':
                self.log(
                    "CHANGED: network interface {0} does not exist but requested state is "
                    "'present'".format(self.name))
                changed = True

        self.results['changed'] = changed
        self.results['state'] = results

        if self.check_mode:
            return self.results

        if changed:
            if self.state == 'present':
                if not nic:
                    # create network interface
                    self.log("Creating network interface {0}.".format(
                        self.name))

                    # check required parameters
                    if not self.subnet_name:
                        self.fail(
                            "parameter error: subnet_name required when creating a network interface."
                        )
                    if not self.virtual_network_name:
                        self.fail(
                            "parameter error: virtual_network_name required when creating a network interface."
                        )

                    if not self.security_group_name:
                        # create default security group
                        nsg = self.create_default_securitygroup(
                            self.resource_group, self.location, self.name,
                            self.os_type, self.open_ports)

                    if not pip and self.public_ip:
                        # create a default public_ip
                        pip = self.create_default_pip(
                            self.resource_group, self.location, self.name,
                            self.public_ip_allocation_method)

                    nic = NetworkInterface(
                        location=self.location,
                        name=self.name,
                        tags=self.tags,
                        ip_configurations=[
                            NetworkInterfaceIPConfiguration(
                                name='default',
                                private_ip_allocation_method=self.
                                private_ip_allocation_method,
                            )
                        ])
                    nic.ip_configurations[0].subnet = Subnet(id=subnet.id)
                    nic.network_security_group = NetworkSecurityGroup(
                        id=nsg.id,
                        name=nsg.name,
                        location=nsg.location,
                        resource_guid=nsg.resource_guid)
                    if self.private_ip_address:
                        nic.ip_configurations[
                            0].private_ip_address = self.private_ip_address

                    if pip:
                        nic.ip_configurations[
                            0].public_ip_address = PublicIPAddress(
                                id=pip.id,
                                name=pip.name,
                                location=pip.location,
                                resource_guid=pip.resource_guid)
                else:
                    self.log("Updating network interface {0}.".format(
                        self.name))
                    nic = NetworkInterface(
                        location=results['location'],
                        name=results['name'],
                        tags=results['tags'],
                        ip_configurations=[
                            NetworkInterfaceIPConfiguration(
                                name=results['ip_configuration']['name'],
                                private_ip_allocation_method=results[
                                    'ip_configuration']
                                ['private_ip_allocation_method'],
                            )
                        ],
                    )
                    subnet = self.get_subnet(
                        results['ip_configuration']['subnet']
                        ['virtual_network_name'],
                        results['ip_configuration']['subnet']['name'])
                    nic.ip_configurations[0].subnet = Subnet(id=subnet.id)

                    if results['ip_configuration'].get('private_ip_address'):
                        nic.ip_configurations[0].private_ip_address = results[
                            'ip_configuration']['private_ip_address']

                    if results['ip_configuration']['public_ip_address'].get(
                            'id'):
                        pip = \
                            self.get_public_ip_address(results['ip_configuration']['public_ip_address']['name'])
                        nic.ip_configurations[
                            0].public_ip_address = PublicIPAddress(
                                id=pip.id,
                                name=pip.name,
                                location=pip.location,
                                resource_guid=pip.resource_guid)

                    if results['network_security_group'].get('id'):
                        nsg = self.get_security_group(
                            results['network_security_group']['name'])
                        nic.network_security_group = NetworkSecurityGroup(
                            id=nsg.id,
                            name=nsg.name,
                            location=nsg.location,
                            resource_guid=nsg.resource_guid)

                # See what actually gets sent to the API
                request = self.serialize_obj(nic, 'NetworkInterface')
                self.log(request, pretty_print=True)

                self.results['state'] = self.create_or_update_nic(nic)

            elif self.state == 'absent':
                self.log('Deleting network interface {0}'.format(self.name))
                self.delete_nic()

        return self.results
Exemplo n.º 14
0
    def create_network_interface(network_client, region, group_name, interface_name,
                                 network_name, subnet_name, ip_name):

        result = network_client.virtual_networks.create_or_update(
            group_name,
            network_name,
            VirtualNetwork(
                location=region,
                address_space=AddressSpace(
                    address_prefixes=[
                        '10.1.0.0/16',
                    ],
                ),
                subnets=[
                    Subnet(
                        name=subnet_name,
                        address_prefix='10.1.0.0/24',
                    ),
                ],
            ),
        )

        print('Creating Virtual Network...')
        result.wait() # async operation

        subnet = network_client.subnets.get(group_name, network_name, subnet_name)
        result = network_client.public_ip_addresses.create_or_update(
            group_name,
            ip_name,
            PublicIPAddress(
                location=region,
                public_ip_allocation_method=IPAllocationMethod.dynamic,
                idle_timeout_in_minutes=4,
            ),
        )

        print('Creating Subnet...')
        result.wait() # async operation

        # Creating Public IP
        public_ip_address = network_client.public_ip_addresses.get(group_name, ip_name)
        public_ip_id = public_ip_address.id

        print('Creating Public IP...')
        result.wait() # async operation

        result = network_client.network_interfaces.create_or_update(
            group_name,
            interface_name,
            NetworkInterface(
                location=region,
                ip_configurations=[
                    NetworkInterfaceIPConfiguration(
                        name='default',
                        private_ip_allocation_method=IPAllocationMethod.dynamic,
                        subnet=subnet,
                        public_ip_address=PublicIPAddress(
                            id=public_ip_id,
                        ),
                    ),
                ],
            ),
        )

        print('Creating Network Interface...')
        result.wait() # async operation

        network_interface = network_client.network_interfaces.get(
            group_name,
            interface_name,
        )

        return network_interface.id
Exemplo n.º 15
0
    def exec_module(self, **kwargs):

        for key in self.module_arg_spec.keys() + ['tags']:
            setattr(self, key, kwargs[key])

        results = dict()
        changed = False
        nic = None
        subnet = None
        nsg = None
        pip = None

        resource_group = self.get_resource_group(self.resource_group)
        if not self.location:
            # Set default location
            self.location = resource_group.location

        if not NAME_PATTERN.match(self.name):
            self.fail("Parameter error: name must begin with a letter or number, end with a letter or number "
                      "and contain at least one number.")

        if self.state == 'present':
            if self.virtual_network_name and not self.subnet_name:
                self.fail("Parameter error: a subnet is required when passing a virtual_network_name.")

            if self.subnet_name and not self.virtual_network_name:
                self.fail("Parameter error: virtual_network_name is required when passing a subnet value.")

            if self.virtual_network_name and self.subnet_name:
                subnet = self.get_subnet(self.virtual_network_name, self.subnet_name)

            if self.public_ip_address_name:
                pip = self.get_public_ip_address(self.public_ip_address_name)

            if self.security_group_name:
                nsg = self.get_security_group(self.security_group_name)

        try:
            self.log('Fetching network interface {0}'.format(self.name))
            nic = self.network_client.network_interfaces.get(self.resource_group, self.name)

            self.log('Network interface {0} exists'.format(self.name))
            self.check_provisioning_state(nic, self.state)
            results = nic_to_dict(nic)
            self.log(results, pretty_print=True)

            if self.state == 'present':

                update_tags, results['tags'] = self.update_tags(results['tags'])
                if update_tags:
                    changed = True

                if self.private_ip_address:
                    if results['ip_configuration']['private_ip_address'] != self.private_ip_address:
                        self.log("CHANGED: network interface {0} private ip".format(self.name))
                        changed = True
                        results['ip_configuration']['private_ip_address'] = self.private_ip_address

                if self.public_ip_address_name:
                    if results['ip_configuration']['public_ip_address'].get('id') != pip.id:
                        self.log("CHANGED: network interface {0} public ip".format(self.name))
                        changed = True
                        results['ip_configuration']['public_ip_address']['id'] = pip.id
                        results['ip_configuration']['public_ip_address']['name'] = pip.name

                if self.security_group_name:
                    if results['network_security_group'].get('id') != nsg.id:
                        self.log("CHANGED: network interface {0} network security group".format(self.name))
                        changed = True
                        results['network_security_group']['id'] = nsg.id
                        results['network_security_group']['name'] = nsg.name

                if self.private_ip_allocation_method:
                    if results['ip_configuration']['private_ip_allocation_method'] != self.private_ip_allocation_method:
                        self.log("CHANGED: network interface {0} private ip allocation".format(self.name))
                        changed = True
                        results['ip_configuration']['private_ip_allocation_method'] = self.private_ip_allocation_method
                        if self.private_ip_allocation_method == 'Dynamic':
                            results['ip_configuration']['private_ip_address'] = None

                if self.subnet_name:
                    if results['ip_configuration']['subnet'].get('id') != subnet.id:
                        changed = True
                        self.log("CHANGED: network interface {0} subnet".format(self.name))
                        results['ip_configuration']['subnet']['id'] = subnet.id
                        results['ip_configuration']['subnet']['name'] = subnet.name
                        results['ip_configuration']['subnet']['virtual_network_name'] = self.virtual_network_name

            elif self.state == 'absent':
                self.log("CHANGED: network interface {0} exists but requested state is 'absent'".format(self.name))
                changed = True
        except CloudError:
            self.log('Network interface {0} does not exist'.format(self.name))
            if self.state == 'present':
                self.log("CHANGED: network interface {0} does not exist but requested state is "
                         "'present'".format(self.name))
                changed = True

        self.results['changed'] = changed
        self.results['state'] = results

        if self.check_mode:
            return self.results
    
        if changed:
            if self.state == 'present':
                if not nic:
                    # create network interface
                    self.log("Creating network interface {0}.".format(self.name))

                    # check required parameters
                    if not self.subnet_name:
                        self.fail("parameter error: subnet_name required when creating a network interface.")
                    if not self.virtual_network_name:
                        self.fail("parameter error: virtual_network_name required when creating a network interface.")

                    if not self.security_group_name:
                        # create default security group
                        nsg = self.create_default_securitygroup(self.resource_group, self.location, self.name,
                                                                self.os_type, self.open_ports)

                    if not pip and self.public_ip:
                        # create a default public_ip
                        pip = self.create_default_pip(self.resource_group, self.location, self.name,
                                                            self.public_ip_allocation_method)

                    nic = NetworkInterface(
                        location=self.location,
                        name=self.name,
                        tags=self.tags,
                        ip_configurations=[
                            NetworkInterfaceIPConfiguration(
                                name='default',
                                private_ip_allocation_method=self.private_ip_allocation_method,
                            )
                        ]
                    )
                    nic.ip_configurations[0].subnet = Subnet(id=subnet.id)
                    nic.network_security_group = NetworkSecurityGroup(id=nsg.id,
                                                                      name=nsg.name,
                                                                      location=nsg.location,
                                                                      resource_guid=nsg.resource_guid)
                    if self.private_ip_address:
                        nic.ip_configurations[0].private_ip_address = self.private_ip_address

                    if pip:
                        nic.ip_configurations[0].public_ip_address = PublicIPAddress(
                            id=pip.id,
                            name=pip.name,
                            location=pip.location,
                            resource_guid=pip.resource_guid)
                else:
                    self.log("Updating network interface {0}.".format(self.name))
                    nic = NetworkInterface(
                        location=results['location'],
                        name=results['name'],
                        tags=results['tags'],
                        ip_configurations=[
                            NetworkInterfaceIPConfiguration(
                                name=results['ip_configuration']['name'],
                                private_ip_allocation_method=
                                results['ip_configuration']['private_ip_allocation_method'],
                            )
                        ],
                    )
                    subnet = self.get_subnet(results['ip_configuration']['subnet']['virtual_network_name'],
                                             results['ip_configuration']['subnet']['name'])
                    nic.ip_configurations[0].subnet = Subnet(id=subnet.id)

                    if results['ip_configuration'].get('private_ip_address'):
                        nic.ip_configurations[0].private_ip_address = results['ip_configuration']['private_ip_address']

                    if results['ip_configuration']['public_ip_address'].get('id'):
                        pip = \
                            self.get_public_ip_address(results['ip_configuration']['public_ip_address']['name'])
                        nic.ip_configurations[0].public_ip_address = PublicIPAddress(
                            id=pip.id,
                            name=pip.name,
                            location=pip.location,
                            resource_guid=pip.resource_guid)

                    if results['network_security_group'].get('id'):
                        nsg = self.get_security_group(results['network_security_group']['name'])
                        nic.network_security_group = NetworkSecurityGroup(id=nsg.id,
                                                                          name=nsg.name,
                                                                          location=nsg.location,
                                                                          resource_guid=nsg.resource_guid)

                # See what actually gets sent to the API
                request = self.serialize_obj(nic, 'NetworkInterface')
                self.log(request, pretty_print=True)

                self.results['state'] = self.create_or_update_nic(nic)

            elif self.state == 'absent':
                self.log('Deleting network interface {0}'.format(self.name))
                self.delete_nic()

        return self.results