Ejemplo 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)
Ejemplo 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)
Ejemplo n.º 3
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 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()
Ejemplo n.º 5
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))
Ejemplo n.º 6
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()
Ejemplo n.º 7
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
Ejemplo n.º 9
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