Configure Network Interface

    CLI Example:

    .. code-block:: bash

        salt '*' ilo.configure_network [IP ADDRESS] [NETMASK] [GATEWAY]
963641
def configure_network(ip, netmask, gateway):
    '''
    
    '''
    current = network()

    # Check to see if the network is already configured
    if (ip in current['Network Settings']['IP_ADDRESS']['VALUE'] and
            netmask in current['Network Settings']['SUBNET_MASK']['VALUE'] and
            gateway in current['Network Settings']['GATEWAY_IP_ADDRESS']['VALUE']):
        return True

    _xml = """<RIBCL VERSION="2.0">
                <LOGIN USER_LOGIN="adminname" PASSWORD="password">
                  <RIB_INFO MODE="write">
                    <MOD_NETWORK_SETTINGS>
                      <IP_ADDRESS value="{0}"/>
                      <SUBNET_MASK value="{1}"/>
                      <GATEWAY_IP_ADDRESS value="{2}"/>
                    </MOD_NETWORK_SETTINGS>
                  </RIB_INFO>
                </LOGIN>
              </RIBCL> """.format(ip, netmask, gateway)

    return __execute_cmd('Configure_Network', _xml)
653798
def _address_in_network(ip, netaddr, mask):
    
    ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]
    netmask = struct.unpack('=L', socket.inet_aton(mask))[0]
    network = struct.unpack('=L', socket.inet_aton(netaddr))[0] & netmask
    return (ipaddr & netmask) == (network & netmask)
1289917
def add_nat_rule(port, source_interface, dest_interface):
    
    log = logging.getLogger(mod_logger + '.add_nat_rule')
    # Validate args
    if not isinstance(source_interface, basestring):
        msg = 'source_interface argument must be a string'
        log.error(msg)
        raise TypeError(msg)
    if not isinstance(dest_interface, basestring):
        msg = 'dest_interface argument must be a string'
        log.error(msg)
        raise TypeError(msg)

    ip_addresses = ip_addr()
    destination_ip = ip_addresses['eth{i}'.format(i=dest_interface)]
    log.info('Using destination IP address: {d}'.format(d=destination_ip))

    command = ['iptables', '-t', 'nat', '-A', 'PREROUTING', '-i',
               'eth{s}'.format(s=source_interface), '-p', 'tcp',
               '--dport', str(port), '-j', 'DNAT', '--to',
               '{d}:{p}'.format(p=port, d=destination_ip)]
    log.info('Running command: {c}'.format(c=command))
    try:
        subprocess.check_call(command)
    except OSError:
        _, ex, trace = sys.exc_info()
        msg = 'There was a problem running command: {c}\n{e}'.format(c=command, e=str(ex))
        log.error(msg)
        raise OSError, msg, trace
    except subprocess.CalledProcessError:
        _, ex, trace = sys.exc_info()
        msg = 'Command returned a non-zero exit code: {c}\n{e}'.format(c=command, e=str(ex))
        log.error(msg)
        raise OSError, msg, trace
    else:
        log.info('Successfully ran command: {c}'.format(c=command))

    # Save the iptables with the new NAT rule
    try:
        save_iptables()
    except OSError:
        _, ex, trace = sys.exc_info()
        msg = 'OSError: There was a problem saving iptables rules\n{e}'.format(e=str(ex))
        raise OSError, msg, trace
    log.info('Successfully saved iptables rules with the NAT rule')
759761
def add_router_interface(self, context, router_id, interface_info):
        """"""

        new_router = super(AristaL3ServicePlugin, self).add_router_interface(
            context, router_id, interface_info)

        core = directory.get_plugin()

        # Get network info for the subnet that is being added to the router.
        # Check if the interface information is by port-id or subnet-id
        add_by_port, add_by_sub = self._validate_interface_info(interface_info)
        if add_by_sub:
            subnet = core.get_subnet(context, interface_info['subnet_id'])
        elif add_by_port:
            port = core.get_port(context, interface_info['port_id'])
            subnet_id = port['fixed_ips'][0]['subnet_id']
            subnet = core.get_subnet(context, subnet_id)
        network_id = subnet['network_id']

        # To create SVI's in Arista HW, the segmentation Id is required
        # for this network.
        ml2_db = NetworkContext(self, context, {'id': network_id})
        seg_id = ml2_db.network_segments[0]['segmentation_id']

        # Package all the info needed for Hw programming
        router = self.get_router(context, router_id)
        router_info = copy.deepcopy(new_router)
        router_info['seg_id'] = seg_id
        router_info['name'] = router['name']
        router_info['cidr'] = subnet['cidr']
        router_info['gip'] = subnet['gateway_ip']
        router_info['ip_version'] = subnet['ip_version']

        try:
            self.driver.add_router_interface(context, router_info)
            return new_router
        except Exception:
            with excutils.save_and_reraise_exception():
                LOG.error(_LE("Error Adding subnet %(subnet)s to "
                              "router %(router_id)s on Arista HW"),
                          {'subnet': subnet, 'router_id': router_id})
                super(AristaL3ServicePlugin, self).remove_router_interface(
                    context,
                    router_id,
                    interface_info)
1326745
def __ip_addr(addr, address_family=socket.AF_INET):
    '''
    
    '''
    mask_max = '32'
    if address_family == socket.AF_INET6:
        mask_max = '128'

    try:
        if '/' not in addr:
            addr = '{addr}/{mask_max}'.format(addr=addr, mask_max=mask_max)
    except TypeError:
        return False

    ip, mask = addr.rsplit('/', 1)

    # Verify that IP address is valid
    try:
        socket.inet_pton(address_family, ip)
    except socket.error:
        return False

    # Verify that mask is valid
    try:
        mask = int(mask)
    except ValueError:
        return False
    else:
        if not 1 <= mask <= int(mask_max):
            return False

    return True
40291
def set_address(network, address):
    
    if network.find('.//ip') is not None:
        raise RuntimeError("Address already specified in XML configuration.")

    netmask = str(address.netmask)
    ipv4 = str(address[1])
    dhcp_start = str(address[2])
    dhcp_end = str(address[-2])
    ip = etree.SubElement(network, 'ip', address=ipv4, netmask=netmask)
    dhcp = etree.SubElement(ip, 'dhcp')

    etree.SubElement(dhcp, 'range', start=dhcp_start, end=dhcp_end)
497077
def _create_network_interface(
        self, ip_config_name, nic_name, public_ip, region,
        resource_group_name, subnet, accelerated_networking=False
    ):
        
        nic_config = {
            'location': region,
            'ip_configurations': [{
                'name': ip_config_name,
                'private_ip_allocation_method': 'Dynamic',
                'subnet': {
                    'id': subnet.id
                },
                'public_ip_address': {
                    'id': public_ip.id
                },
            }]
        }

        if accelerated_networking:
            nic_config['enable_accelerated_networking'] = True

        try:
            nic_setup = self.network.network_interfaces.create_or_update(
                resource_group_name, nic_name, nic_config
            )
        except Exception as error:
            raise AzureCloudException(
                'Unable to create network interface: {0}.'.format(
                    error
                )
            )

        return nic_setup.result()
187648
def _interfaces_ifconfig(out):
    
    ret = dict()

    piface = re.compile(r'^([^\s:]+)')
    pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)')
    pip = re.compile(r'.*?(?:inet addr:|inet )(.*?)\s')
    pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)')
    pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))')
    pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+)).*')
    pupdown = re.compile('UP')
    pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)')

    groups = re.compile('\r?\n(?=\\S)').split(out)
    for group in groups:
        data = dict()
        iface = ''
        updown = False
        for line in group.splitlines():
            miface = piface.match(line)
            mmac = pmac.match(line)
            mip = pip.match(line)
            mip6 = pip6.match(line)
            mupdown = pupdown.search(line)
            if miface:
                iface = miface.group(1)
            if mmac:
                data['hwaddr'] = mmac.group(1)
            if mip:
                if 'inet' not in data:
                    data['inet'] = list()
                addr_obj = dict()
                addr_obj['address'] = mip.group(1)
                mmask = pmask.match(line)
                if mmask:
                    if mmask.group(1):
                        mmask = _number_of_set_bits_to_ipv4_netmask(
                            int(mmask.group(1), 16))
                    else:
                        mmask = mmask.group(2)
                    addr_obj['netmask'] = mmask
                mbcast = pbcast.match(line)
                if mbcast:
                    addr_obj['broadcast'] = mbcast.group(1)
                data['inet'].append(addr_obj)
            if mupdown:
                updown = True
            if mip6:
                if 'inet6' not in data:
                    data['inet6'] = list()
                addr_obj = dict()
                addr_obj['address'] = mip6.group(1) or mip6.group(2)
                mmask6 = pmask6.match(line)
                if mmask6:
                    addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2)
                data['inet6'].append(addr_obj)
        data['up'] = updown
        ret[iface] = data
        del data
    return ret
509606
def _configured_socket(address, options):
    
    sock = _create_connection(address, options)
    ssl_context = options.ssl_context

    if ssl_context is not None:
        host = address[0]
        try:
            # According to RFC6066, section 3, IPv4 and IPv6 literals are
            # not permitted for SNI hostname.
            if _HAVE_SNI and not is_ip_address(host):
                sock = ssl_context.wrap_socket(sock, server_hostname=host)
            else:
                sock = ssl_context.wrap_socket(sock)
        except IOError as exc:
            sock.close()
            raise ConnectionFailure("SSL handshake failed: %s" % (str(exc),))
        if ssl_context.verify_mode and options.ssl_match_hostname:
            try:
                match_hostname(sock.getpeercert(), hostname=host)
            except CertificateError:
                sock.close()
                raise

    sock.settimeout(options.socket_timeout)
    return sock
126268
def delete_interface(call=None, kwargs=None):  # pylint: disable=unused-argument
    '''
    
    '''
    if kwargs is None:
        kwargs = {}

    netconn = get_conn(client_type='network')

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

    ips = []
    iface = netconn.network_interfaces.get(
        kwargs['resource_group'],
        kwargs['iface_name'],
    )
    iface_name = iface.name
    for ip_ in iface.ip_configurations:
        ips.append(ip_.name)

    poller = netconn.network_interfaces.delete(
        kwargs['resource_group'],
        kwargs['iface_name'],
    )
    poller.wait()

    for ip_ in ips:
        poller = netconn.public_ip_addresses.delete(kwargs['resource_group'], ip_)
        poller.wait()

    return {iface_name: ips}
304339
def resolve_network_cidr(ip_address):
    '''
    
    '''
    netmask = get_netmask_for_address(ip_address)
    return str(netaddr.IPNetwork("%s/%s" % (ip_address, netmask)).cidr)
1261696
def updateNetwork(self,
                      dhcp='dhcp',
                      ipaddress=None,
                      netmask=None,
                      gateway=None,
                      dns=None):
        """"""
        return self.__post('/api/updateNetwork',
                           data={
                               'dhcp': dhcp,
                               'ipaddress': ipaddress,
                               'netmask': netmask,
                               'gateway': gateway,
                               'dns': json.dumps(dns)
                           })
1117372
def create_network_interface(call=None, kwargs=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The create_network_interface action must be called with -a or --action.'
        )

    # pylint: disable=invalid-name
    IPAllocationMethod = getattr(
        network_models,
        'IPAllocationMethod'
    )
    # pylint: disable=invalid-name
    NetworkInterface = getattr(
        network_models,
        'NetworkInterface'
    )
    # pylint: disable=invalid-name
    NetworkInterfaceIPConfiguration = getattr(
        network_models,
        'NetworkInterfaceIPConfiguration'
    )
    # pylint: disable=invalid-name
    PublicIPAddress = getattr(
        network_models,
        'PublicIPAddress'
    )

    if not isinstance(kwargs, dict):
        kwargs = {}

    vm_ = kwargs
    netconn = get_conn(client_type='network')

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

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

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

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

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

    try:
        subnet_obj = netconn.subnets.get(
            resource_group_name=kwargs['network_resource_group'],
            virtual_network_name=kwargs['network'],
            subnet_name=kwargs['subnet'],
        )
    except CloudError as exc:
        raise SaltCloudSystemExit(
            '{0} (Resource Group: "{1}", VNET: "{2}", Subnet: "{3}")'.format(
                exc.message,
                kwargs['network_resource_group'],
                kwargs['network'],
                kwargs['subnet']
            )
        )

    ip_kwargs = {}
    ip_configurations = None

    if 'load_balancer_backend_address_pools' in kwargs:
        pool_dicts = kwargs['load_balancer_backend_address_pools']
        if isinstance(pool_dicts, dict):
            pool_ids = []
            for load_bal, be_pools in pool_dicts.items():
                for pool in be_pools:
                    try:
                        lbbep_data = netconn.load_balancer_backend_address_pools.get(
                            kwargs['resource_group'],
                            load_bal,
                            pool,
                        )
                        pool_ids.append({'id': lbbep_data.as_dict()['id']})
                    except CloudError as exc:
                        log.error('There was a cloud error: %s', six.text_type(exc))
                    except KeyError as exc:
                        log.error('There was an error getting the Backend Pool ID: %s', six.text_type(exc))
            ip_kwargs['load_balancer_backend_address_pools'] = pool_ids

    if 'private_ip_address' in kwargs.keys():
        ip_kwargs['private_ip_address'] = kwargs['private_ip_address']
        ip_kwargs['private_ip_allocation_method'] = IPAllocationMethod.static
    else:
        ip_kwargs['private_ip_allocation_method'] = IPAllocationMethod.dynamic

    if kwargs.get('allocate_public_ip') 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'] = PublicIPAddress(
                        id=six.text_type(pub_ip_data.id),  # pylint: disable=no-member
                    )
                    ip_configurations = [
                        NetworkInterfaceIPConfiguration(
                            name='{0}-ip'.format(kwargs['iface_name']),
                            subnet=subnet_obj,
                            **ip_kwargs
                        )
                    ]
                    break
            except CloudError as exc:
                log.error('There was a cloud error: %s', exc)
            count += 1
            if count > 120:
                raise ValueError('Timed out waiting for public IP Address.')
            time.sleep(5)
    else:
        priv_ip_name = '{0}-ip'.format(kwargs['iface_name'])
        ip_configurations = [
            NetworkInterfaceIPConfiguration(
                name=priv_ip_name,
                subnet=subnet_obj,
                **ip_kwargs
            )
        ]

    network_security_group = None
    if kwargs.get('security_group') is not None:
        network_security_group = netconn.network_security_groups.get(
            resource_group_name=kwargs['resource_group'],
            network_security_group_name=kwargs['security_group'],
        )

    iface_params = NetworkInterface(
        location=kwargs['location'],
        network_security_group=network_security_group,
        ip_configurations=ip_configurations,
    )

    poller = netconn.network_interfaces.create_or_update(
        kwargs['resource_group'], kwargs['iface_name'], iface_params
    )
    try:
        poller.wait()
    except Exception as exc:
        log.warning('Network interface creation could not be polled. '
                 'It is likely that we are reusing an existing interface. (%s)', exc)

    count = 0
    while True:
        try:
            return _get_network_interface(kwargs['iface_name'], kwargs['resource_group'])
        except CloudError:
            count += 1
            if count > 120:
                raise ValueError('Timed out waiting for operation to complete.')
            time.sleep(5)
1281350
def set_ddns_config(self, isenable, hostname, ddnsserver,
                                        user, password, callback=None):
        '''
        
        '''
        params = {'isEnable': isenable,
                  'hostName': hostname,
                  'ddnsServer': ddnsserver,
                  'user': user,
                  'password': password,
                 }
        return self.execute_command('setDDNSConfig', params, callback=callback)
1272781
def ingress_interface
      list = config_get('itd_service', 'ingress_interface', @get_args)
      rlist = []
      list.each do |intf, next_hop|
        intf.gsub!('Eth', 'ethernet ')
        intf.gsub!('Po', 'port-channel ')
        intf.gsub!('Vlan', 'vlan ')
        next_hop = '' if next_hop.nil?
        rlist << [intf, next_hop]
      end
      rlist
    end
293507
def _interfaces_ifconfig(out):
    '''
    
    '''
    ret = dict()

    piface = re.compile(r'^([^\s:]+)')
    pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)')
    if salt.utils.platform.is_sunos():
        pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)')
        pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)')
        pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*')
    else:
        pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s')
        pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)')
        pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?')
    pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))')
    pupdown = re.compile('UP')
    pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)')

    groups = re.compile('\r?\n(?=\\S)').split(out)
    for group in groups:
        data = dict()
        iface = ''
        updown = False
        for line in group.splitlines():
            miface = piface.match(line)
            mmac = pmac.match(line)
            mip = pip.match(line)
            mip6 = pip6.match(line)
            mupdown = pupdown.search(line)
            if miface:
                iface = miface.group(1)
            if mmac:
                data['hwaddr'] = mmac.group(1)
                if salt.utils.platform.is_sunos():
                    expand_mac = []
                    for chunk in data['hwaddr'].split(':'):
                        expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk))
                    data['hwaddr'] = ':'.join(expand_mac)
            if mip:
                if 'inet' not in data:
                    data['inet'] = list()
                addr_obj = dict()
                addr_obj['address'] = mip.group(1)
                mmask = pmask.match(line)
                if mmask:
                    if mmask.group(1):
                        mmask = _number_of_set_bits_to_ipv4_netmask(
                            int(mmask.group(1), 16))
                    else:
                        mmask = mmask.group(2)
                    addr_obj['netmask'] = mmask
                mbcast = pbcast.match(line)
                if mbcast:
                    addr_obj['broadcast'] = mbcast.group(1)
                data['inet'].append(addr_obj)
            if mupdown:
                updown = True
            if mip6:
                if 'inet6' not in data:
                    data['inet6'] = list()
                addr_obj = dict()
                addr_obj['address'] = mip6.group(1) or mip6.group(2)
                mmask6 = pmask6.match(line)
                if mmask6:
                    addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2)
                    if not salt.utils.platform.is_sunos():
                        ipv6scope = mmask6.group(3) or mmask6.group(4)
                        addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope
                # SunOS sometimes has ::/0 as inet6 addr when using addrconf
                if not salt.utils.platform.is_sunos() \
                        or addr_obj['address'] != '::' \
                        and addr_obj['prefixlen'] != 0:
                    data['inet6'].append(addr_obj)
        data['up'] = updown
        if iface in ret:
            # SunOS optimization, where interfaces occur twice in 'ifconfig -a'
            # output with the same name: for ipv4 and then for ipv6 addr family.
            # Every instance has it's own 'UP' status and we assume that ipv4
            # status determines global interface status.
            #
            # merge items with higher priority for older values
            # after that merge the inet and inet6 sub items for both
            ret[iface] = dict(list(data.items()) + list(ret[iface].items()))
            if 'inet' in data:
                ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet'])
            if 'inet6' in data:
                ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6'])
        else:
            ret[iface] = data
        del data
    return ret
1104083
def network(ip, netmask, gateway):
    '''
    
    '''
    ret = {'name': ip,
           'result': True,
           'changes': {},
           'comment': ''}

    current_network = __salt__['drac.network_info']()
    new_network = {}

    if ip != current_network['IPv4 settings']['IP Address']:
        ret['changes'].update({'IP Address':
                              {'Old': current_network['IPv4 settings']['IP Address'],
                               'New': ip}})

    if netmask != current_network['IPv4 settings']['Subnet Mask']:
        ret['changes'].update({'Netmask':
                              {'Old': current_network['IPv4 settings']['Subnet Mask'],
                               'New': netmask}})

    if gateway != current_network['IPv4 settings']['Gateway']:
        ret['changes'].update({'Gateway':
                              {'Old': current_network['IPv4 settings']['Gateway'],
                               'New': gateway}})

    if __opts__['test']:
        ret['result'] = None
        return ret

    if __salt__['drac.set_network'](ip, netmask, gateway):
        if not ret['changes']:
            ret['comment'] = 'Network is in the desired state'

        return ret

    ret['result'] = False
    ret['comment'] = 'unable to configure network'

    return ret