Example #1
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)
Example #2
0
def create_nic_ip_config(
        resource_group_name,
        network_interface_name,
        ip_config_name,
        subnet=None,
        virtual_network_name=None,
        public_ip_address=None,
        load_balancer_name=None,  # pylint: disable=unused-argument
        load_balancer_backend_address_pool_ids=None,
        load_balancer_inbound_nat_rule_ids=None,
        private_ip_address=None,
        private_ip_address_allocation='dynamic',
        private_ip_address_version='ipv4'):
    ncf = _network_client_factory()
    nic = ncf.network_interfaces.get(resource_group_name,
                                     network_interface_name)
    nic.ip_configurations.append(
        NetworkInterfaceIPConfiguration(
            name=ip_config_name,
            subnet=Subnet(subnet) if subnet else None,
            public_ip_address=PublicIPAddress(public_ip_address)
            if public_ip_address else None,
            load_balancer_backend_address_pools=
            load_balancer_backend_address_pool_ids,
            load_balancer_inbound_nat_rules=load_balancer_inbound_nat_rule_ids,
            private_ip_address=private_ip_address,
            private_ip_allocation_method=private_ip_address_allocation,
            private_ip_address_version=private_ip_address_version))
    return ncf.network_interfaces.create_or_update(resource_group_name,
                                                   network_interface_name, nic)
 def get(self, resource_group_name: str, public_ip_address_name: str) -> PublicIPAddress:
     try:
         with open(self.path / resource_group_name / f"ip-{public_ip_address_name}.json", "r",
                   encoding="utf-8") as file:
             return PublicIPAddress.deserialize(json.load(file))
     except FileNotFoundError:
         raise ResourceNotFoundError("Public IP address not found") from None
Example #4
0
def set_lb_frontend_ip_configuration(resource_group_name,
                                     load_balancer_name,
                                     item_name,
                                     private_ip_address=None,
                                     private_ip_address_allocation=None,
                                     public_ip_address=None,
                                     subnet=None,
                                     virtual_network_name=None):  # pylint: disable=unused-argument
    ncf = _network_client_factory()
    lb = ncf.load_balancers.get(resource_group_name, load_balancer_name)
    item = _get_property(lb.frontend_ip_configurations, item_name)

    if private_ip_address == '':
        item.private_ip_allocation_method = private_ip_address_allocation
        item.private_ip_address = None
    elif private_ip_address is not None:
        item.private_ip_allocation_method = private_ip_address_allocation
        item.private_ip_address = private_ip_address

    if subnet == '':
        item.subnet = None
    elif subnet is not None:
        item.subnet = Subnet(subnet)

    if public_ip_address == '':
        item.public_ip_address = None
    elif public_ip_address is not None:
        item.public_ip_address = PublicIPAddress(public_ip_address)

    return ncf.load_balancers.create_or_update(resource_group_name,
                                               load_balancer_name, lb)
 def list(self, resource_group_name: str) -> List[PublicIPAddress]:
     try:
         files = [file for file in os.listdir(self.path / resource_group_name) if file.startswith("ip-")]
     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(PublicIPAddress.deserialize(json.load(file)))
     return elements
Example #6
0
def set_nic_ip_config(
        resource_group_name,
        network_interface_name,
        ip_config_name,
        subnet=None,
        virtual_network_name=None,
        public_ip_address=None,
        load_balancer_name=None,  # pylint: disable=unused-argument
        load_balancer_backend_address_pool_ids=None,
        load_balancer_inbound_nat_rule_ids=None,
        private_ip_address=None,
        private_ip_address_allocation=None,  # pylint: disable=unused-argument
        private_ip_address_version='ipv4'):
    ncf = _network_client_factory()
    nic = ncf.network_interfaces.get(resource_group_name,
                                     network_interface_name)
    ip_config = _get_property(nic.ip_configurations, ip_config_name)

    if private_ip_address == '':
        ip_config.private_ip_address = None
        ip_config.private_ip_allocation_method = 'dynamic'
        ip_config.private_ip_address_version = 'ipv4'
    elif private_ip_address is not None:
        ip_config.private_ip_address = private_ip_address
        ip_config.private_ip_allocation_method = 'static'
        if private_ip_address_version is not None:
            ip_config.private_ip_address_version = private_ip_address_version

    if subnet == '':
        ip_config.subnet = None
    elif subnet is not None:
        ip_config.subnet = Subnet(subnet)

    if public_ip_address == '':
        ip_config.public_ip_address = None
    elif public_ip_address is not None:
        ip_config.public_ip_address = PublicIPAddress(public_ip_address)

    if load_balancer_backend_address_pool_ids == '':
        ip_config.load_balancer_backend_address_pools = None
    elif load_balancer_backend_address_pool_ids is not None:
        ip_config.load_balancer_backend_address_pools = load_balancer_backend_address_pool_ids

    if load_balancer_inbound_nat_rule_ids == '':
        ip_config.load_balancer_inbound_nat_rules = None
    elif load_balancer_inbound_nat_rule_ids is not None:
        ip_config.load_balancer_inbound_nat_rules = load_balancer_inbound_nat_rule_ids

    return ncf.network_interfaces.create_or_update(resource_group_name,
                                                   network_interface_name, nic)
Example #7
0
    def create_default_pip(self,
                           resource_group,
                           location,
                           name,
                           allocation_method='Dynamic'):
        '''
        Create a default public IP address <name>01 to associate with a network interface.
        If a PIP address matching <vm name>01 exists, return it. Otherwise, create one.

        :param resource_group: name of an existing resource group
        :param location: a valid azure location
        :param name: base name to assign the public IP address
        :param allocation_method: one of 'Static' or 'Dynamic'
        :return: PIP object
        '''
        public_ip_name = name + '01'
        pip = None

        self.log("Starting create_default_pip {0}".format(public_ip_name))
        self.log("Check to see if public IP {0} exists".format(public_ip_name))
        try:
            pip = self.network_client.public_ip_addresses.get(
                resource_group, public_ip_name)
        except CloudError:
            pass

        if pip:
            self.log("Public ip {0} found.".format(public_ip_name))
            self.check_provisioning_state(pip)
            return pip

        params = PublicIPAddress(
            location=location,
            public_ip_allocation_method=allocation_method,
        )
        self.log('Creating default public IP {0}'.format(public_ip_name))
        try:
            poller = self.network_client.public_ip_addresses.create_or_update(
                resource_group, public_ip_name, params)
        except Exception as exc:
            self.fail("Error creating {0} - {1}".format(
                public_ip_name, str(exc)))

        return self.get_poller_result(poller)
Example #8
0
def create_lb_frontend_ip_configuration(
        resource_group_name,
        load_balancer_name,
        item_name,
        public_ip_address=None,
        subnet=None,
        virtual_network_name=None,
        private_ip_address=None,  # pylint: disable=unused-argument
        private_ip_address_allocation='dynamic'):
    ncf = _network_client_factory()
    lb = ncf.load_balancers.get(resource_group_name, load_balancer_name)
    lb.frontend_ip_configurations.append(
        FrontendIPConfiguration(
            name=item_name,
            private_ip_address=private_ip_address,
            private_ip_allocation_method=private_ip_address_allocation,
            public_ip_address=PublicIPAddress(public_ip_address)
            if public_ip_address else None,
            subnet=Subnet(subnet) if subnet else None))
    return ncf.load_balancers.create_or_update(resource_group_name,
                                               load_balancer_name, lb)
Example #9
0
    def create_pip(self, rg_name, location, pip_name, allocation_method="Dynamic"):
        """ Create public IP in given resource group.

        Args:
            rg_name (str): Azure resource group name
            location (str): Azure public IP location
                            (needs to be the same as resource group location)
            pip_name (str): public IP name
            allocation_method (str): IP allocation metod (Dynamic, Static)
        """
        params = PublicIPAddress(
            location=location, public_ip_allocation_method=allocation_method
        )
        try:
            poller_obj = self.network_client.public_ip_addresses.create_or_update(
                rg_name, pip_name, params
            )
        except CloudError as cloud_err:
            self.colored_print(cloud_err.__repr__(), level="error")
            raise
        poller_obj.wait()
 def _create_public_ip_address(
     self, tag: str, location: str, resource_group_name: str
 ) -> PublicIPAddress:
     """
     Creates a public ip address to the defined resource group and location.
     Returns an instance of PublicIPAddress.
     This is a long running operation and it blocks until the IP address is created.
     """
     pip_suffix = random_name_generator()
     logging.debug("Creating a public IP address with tag '%s'", tag)
     return self.network.public_ip_addresses.begin_create_or_update(
         resource_group_name=resource_group_name,
         public_ip_address_name=f"publicip-{pip_suffix}",
         parameters=PublicIPAddress(
             location=location,
             tags=get_policy_tags(additional_tags={TAG_APPGWGROUP: tag}),
             sku=PublicIPAddressSku(name="Standard"),
             public_ip_allocation_method="Static",
             public_ip_address_version="IPv4",
             dns_settings=PublicIPAddressDnsSettings(
                 domain_name_label=f"pip-{pip_suffix}"
             ),
         ),
     ).result()
Example #11
0
    def exec_module(self, **kwargs):

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

        results = dict()
        changed = False
        pip = None

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

        try:
            self.log("Fetch public ip {0}".format(self.name))
            pip = self.network_client.public_ip_addresses.get(self.resource_group, self.name)
            self.check_provisioning_state(pip, self.state)
            self.log("PIP {0} exists".format(self.name))
            if self.state == 'present':
                results = pip_to_dict(pip)
                if self.domain_name != results['dns_settings'].get('domain_name_label'):
                    self.log('CHANGED: domain_name_label')
                    changed = True
                    results['dns_settings']['domain_name_label'] =self.domain_name

                if self.allocation_method != results['public_ip_allocation_method']:
                    self.log("CHANGED: allocation_method")
                    changed = True
                    results['public_ip_allocation_method'] = self.allocation_method

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

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

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

        if self.check_mode:
            return results

        if changed:
            if self.state == 'present':
                if not pip:
                    self.log("Create new Public IP {0}".format(self.name))
                    pip = PublicIPAddress(
                        location=self.location,
                        public_ip_allocation_method=self.allocation_method,
                    )
                    if self.tags:
                        pip.tags = self.tags
                    if self.domain_name:
                        pip.dns_settings = PublicIPAddressDnsSettings(
                            domain_name_label=self.domain_name
                        )
                else:
                    self.log("Update Public IP {0}".format(self.name))
                    pip = PublicIPAddress(
                        location=results['location'],
                        public_ip_allocation_method=results['public_ip_allocation_method'],
                        tags=results['tags']
                    )
                    if self.domain_name:
                        pip.dns_settings = PublicIPAddressDnsSettings(
                            domain_name_label=self.domain_name
                        )
                self.results['state'] = self.create_or_update_pip(pip)
            elif self.state == 'absent':
                self.log('Delete public ip {0}'.format(self.name))
                self.delete_pip()

        return self.results
Example #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)
Example #13
0
    def exec_module(self, **kwargs):

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

        results = dict()
        changed = False
        pip = None

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

        try:
            self.log("Fetch public ip {0}".format(self.name))
            pip = self.network_client.public_ip_addresses.get(self.resource_group, self.name)
            self.check_provisioning_state(pip, self.state)
            self.log("PIP {0} exists".format(self.name))
            if self.state == 'present':
                results = pip_to_dict(pip)
                if self.domain_name != results['dns_settings'].get('domain_name_label'):
                    self.log('CHANGED: domain_name_label')
                    changed = True
                    results['dns_settings']['domain_name_label'] =self.domain_name

                if self.allocation_method != results['public_ip_allocation_method']:
                    self.log("CHANGED: allocation_method")
                    changed = True
                    results['public_ip_allocation_method'] = self.allocation_method

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

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

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

        if self.check_mode:
            return results

        if changed:
            if self.state == 'present':
                if not pip:
                    self.log("Create new Public IP {0}".format(self.name))
                    pip = PublicIPAddress(
                        location=self.location,
                        public_ip_allocation_method=self.allocation_method,
                    )
                    if self.tags:
                        pip.tags = self.tags
                    if self.domain_name:
                        pip.dns_settings = PublicIPAddressDnsSettings(
                            domain_name_label=self.domain_name
                        )
                else:
                    self.log("Update Public IP {0}".format(self.name))
                    pip = PublicIPAddress(
                        location=results['location'],
                        public_ip_allocation_method=results['public_ip_allocation_method'],
                        tags=results['tags']
                    )
                    if self.domain_name:
                        pip.dns_settings = PublicIPAddressDnsSettings(
                            domain_name_label=self.domain_name
                        )
                self.results['state'] = self.create_or_update_pip(pip)
            elif self.state == 'absent':
                self.log('Delete public ip {0}'.format(self.name))
                self.delete_pip()

        return self.results
    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
Example #15
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