Attempts to describe vpc ids.
336261
def describe_vpc(record):
    """"""
    account_id = record['account']
    vpc_name = cloudwatch.filter_request_parameters('vpcName', record)
    vpc_id = cloudwatch.filter_request_parameters('vpcId', record)

    try:
        if vpc_id and vpc_name:  # pylint: disable=R1705
            return describe_vpcs(
                account_number=account_id,
                assume_role=HISTORICAL_ROLE,
                region=CURRENT_REGION,
                Filters=[
                    {
                        'Name': 'vpc-id',
                        'Values': [vpc_id]
                    }
                ]
            )
        elif vpc_id:
            return describe_vpcs(
                account_number=account_id,
                assume_role=HISTORICAL_ROLE,
                region=CURRENT_REGION,
                VpcIds=[vpc_id]
            )
        else:
            raise Exception('[X] Describe requires VpcId.')
    except ClientError as exc:
        if exc.response['Error']['Code'] == 'InvalidVpc.NotFound':
            return []
        raise exc
537882
public java.util.List<String> getVpcPeeringConnectionIds() {
        if (vpcPeeringConnectionIds == null) {
            vpcPeeringConnectionIds = new com.amazonaws.internal.SdkInternalList<String>();
        }
        return vpcPeeringConnectionIds;
    }
306819
def describe_route_table(route_table_id=None, route_table_name=None,
                         tags=None, region=None, key=None, keyid=None,
                         profile=None):
    '''
    

    '''
    salt.utils.versions.warn_until(
        'Neon',
         'The \'describe_route_table\' method has been deprecated and '
         'replaced by \'describe_route_tables\'.'
    )
    if not any((route_table_id, route_table_name, tags)):
        raise SaltInvocationError('At least one of the following must be specified: '
                                  'route table id, route table name, or tags.')

    try:
        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
        filter_parameters = {'filters': {}}

        if route_table_id:
            filter_parameters['route_table_ids'] = route_table_id

        if route_table_name:
            filter_parameters['filters']['tag:Name'] = route_table_name

        if tags:
            for tag_name, tag_value in six.iteritems(tags):
                filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value

        route_tables = conn.get_all_route_tables(**filter_parameters)

        if not route_tables:
            return {}

        route_table = {}
        keys = ['id', 'vpc_id', 'tags', 'routes', 'associations']
        route_keys = ['destination_cidr_block', 'gateway_id', 'instance_id', 'interface_id', 'vpc_peering_connection_id']
        assoc_keys = ['id', 'main', 'route_table_id', 'subnet_id']
        for item in route_tables:
            for key in keys:
                if hasattr(item, key):
                    route_table[key] = getattr(item, key)
                    if key == 'routes':
                        route_table[key] = _key_iter(key, route_keys, item)
                    if key == 'associations':
                        route_table[key] = _key_iter(key, assoc_keys, item)
        return route_table

    except BotoServerError as e:
        return {'error': __utils__['boto.get_error'](e)}
437118
def client_ident(self):
        
        return irc.client.NickMask.from_params(
            self.nick, self.user,
            self.server.servername)
791480
def _get_ids_from_hostname(self, hostname):
        """"""
        results = self.list_instances(hostname=hostname, mask="id")
        return [result['id'] for result in results]
1286035
def ec2_vpc_subnets(self, lookup, default=None):
    
    vpc_id = self.ec2_vpc_vpc_id(lookup)
    if vpc_id is None:
      return default
    subnets = EFAwsResolver.__CLIENTS["ec2"].describe_subnets(Filters=[{
      'Name': 'vpc-id',
      'Values': [vpc_id]
    }])
    if len(subnets["Subnets"]) > 0:
      # Strip the metadata section (subnets["Subnets"])
      subnet_list = [s["SubnetId"] for s in subnets["Subnets"]]
      # Add internal ", " only. This is called literally from: "{{aws...}}" - reuses the outer quotes
      return "\", \"".join(subnet_list)
    else:
      return default
683175
def describe_group(record, region):
    """"""
    account_id = record['account']
    group_name = cloudwatch.filter_request_parameters('groupName', record)
    vpc_id = cloudwatch.filter_request_parameters('vpcId', record)
    group_id = cloudwatch.filter_request_parameters('groupId', record, look_in_response=True)

    # Did this get collected already by the poller?
    if cloudwatch.get_collected_details(record):
        LOG.debug(f"[<--] Received already collected security group data: {record['detail']['collected']}")
        return [record['detail']['collected']]

    try:
        # Always depend on Group ID first:
        if group_id:  # pylint: disable=R1705
            return describe_security_groups(
                account_number=account_id,
                assume_role=HISTORICAL_ROLE,
                region=region,
                GroupIds=[group_id]
            )['SecurityGroups']

        elif vpc_id and group_name:
            return describe_security_groups(
                account_number=account_id,
                assume_role=HISTORICAL_ROLE,
                region=region,
                Filters=[
                    {
                        'Name': 'group-name',
                        'Values': [group_name]
                    },
                    {
                        'Name': 'vpc-id',
                        'Values': [vpc_id]
                    }
                ]
            )['SecurityGroups']

        else:
            raise Exception('[X] Did not receive Group ID or VPC/Group Name pairs. '
                            f'We got: ID: {group_id} VPC/Name: {vpc_id}/{group_name}.')
    except ClientError as exc:
        if exc.response['Error']['Code'] == 'InvalidGroup.NotFound':
            return []
        raise exc
466417
def securitygroupid(vm_):
    '''
    
    '''
    securitygroupid_set = set()
    securitygroupid_list = config.get_cloud_config_value(
        'securitygroupid',
        vm_,
        __opts__,
        search_global=False
    )
    # If the list is None, then the set will remain empty
    # If the list is already a set then calling 'set' on it is a no-op
    # If the list is a string, then calling 'set' generates a one-element set
    # If the list is anything else, stacktrace
    if securitygroupid_list:
        securitygroupid_set = securitygroupid_set.union(set(securitygroupid_list))

    securitygroupname_list = config.get_cloud_config_value(
        'securitygroupname', vm_, __opts__, search_global=False
    )
    if securitygroupname_list:
        if not isinstance(securitygroupname_list, list):
            securitygroupname_list = [securitygroupname_list]
        params = {'Action': 'DescribeSecurityGroups'}
        for sg in aws.query(params, location=get_location(),
                            provider=get_provider(), opts=__opts__, sigver='4'):
            if sg['groupName'] in securitygroupname_list:
                log.debug(
                    'AWS SecurityGroup ID of %s is %s',
                    sg['groupName'], sg['groupId']
                )
                securitygroupid_set.add(sg['groupId'])
    return list(securitygroupid_set)
799856
def _make_ip_subnet_lookup(vpc_info):
    
    # We create a reverse lookup from the instances private IP addresses to the
    # subnets they are associated with. This is used later on in order to
    # determine whether routes should be set in an RT: Is the RT's subnet
    # associated with ANY of the IP addresses in the route spec? To make this
    # easy, we collect the IPs and subnets of all EC2 instances in the VPC.
    # Once we get a route spec, we create a list of subnets for only the
    # cluster nodes. The assumption is that not all EC2 instances in the VPC
    # necessarily belong to the cluster. We really want to narrow it down to
    # the cluster nodes only. See make_cluster_node_subnet_list().
    vpc_info['ip_subnet_lookup'] = {}
    for instance in vpc_info['instances']:
        for interface in instance.interfaces:
            subnet_id = interface.subnet_id
            for priv_addr in interface.private_ip_addresses:
                vpc_info['ip_subnet_lookup'][priv_addr.private_ip_address] = \
                                                                    subnet_id
995767
def _tags_present(name, tags, vpc_id=None, vpc_name=None, region=None,
                  key=None, keyid=None, profile=None):
    '''
    
    '''
    ret = {'result': True, 'comment': '', 'changes': {}}
    if tags:
        sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
                                                  keyid=keyid, profile=profile, vpc_id=vpc_id,
                                                  vpc_name=vpc_name)
        if not sg:
            ret['comment'] = '{0} security group configuration could not be retrieved.'.format(name)
            ret['result'] = False
            return ret
        tags_to_add = tags
        tags_to_update = {}
        tags_to_remove = []
        if sg.get('tags'):
            for existing_tag in sg['tags']:
                if existing_tag not in tags:
                    if existing_tag not in tags_to_remove:
                        tags_to_remove.append(existing_tag)
                else:
                    if tags[existing_tag] != sg['tags'][existing_tag]:
                        tags_to_update[existing_tag] = tags[existing_tag]
                    tags_to_add.pop(existing_tag)
        if tags_to_remove:
            if __opts__['test']:
                msg = 'The following tag{0} set to be removed: {1}.'.format(
                        ('s are' if len(tags_to_remove) > 1 else ' is'), ', '.join(tags_to_remove))
                ret['comment'] = ' '.join([ret['comment'], msg])
                ret['result'] = None
            else:
                temp_ret = __salt__['boto_secgroup.delete_tags'](tags_to_remove,
                                                                 name=name,
                                                                 group_id=None,
                                                                 vpc_name=vpc_name,
                                                                 vpc_id=vpc_id,
                                                                 region=region,
                                                                 key=key,
                                                                 keyid=keyid,
                                                                 profile=profile)
                if not temp_ret:
                    ret['result'] = False
                    ret['comment'] = ' '.join([
                        ret['comment'],
                        'Error attempting to delete tags {0}.'.format(tags_to_remove)
                    ])
                    return ret
                if 'old' not in ret['changes']:
                    ret['changes'] = dictupdate.update(ret['changes'], {'old': {'tags': {}}})
                for rem_tag in tags_to_remove:
                    ret['changes']['old']['tags'][rem_tag] = sg['tags'][rem_tag]
        if tags_to_add or tags_to_update:
            if __opts__['test']:
                if tags_to_add:
                    msg = 'The following tag{0} set to be added: {1}.'.format(
                            ('s are' if len(tags_to_add.keys()) > 1 else ' is'),
                            ', '.join(tags_to_add.keys()))
                    ret['comment'] = ' '.join([ret['comment'], msg])
                    ret['result'] = None
                if tags_to_update:
                    msg = 'The following tag {0} set to be updated: {1}.'.format(
                            ('values are' if len(tags_to_update.keys()) > 1 else 'value is'),
                            ', '.join(tags_to_update.keys()))
                    ret['comment'] = ' '.join([ret['comment'], msg])
                    ret['result'] = None
            else:
                all_tag_changes = dictupdate.update(tags_to_add, tags_to_update)
                temp_ret = __salt__['boto_secgroup.set_tags'](all_tag_changes,
                                                              name=name,
                                                              group_id=None,
                                                              vpc_name=vpc_name,
                                                              vpc_id=vpc_id,
                                                              region=region,
                                                              key=key,
                                                              keyid=keyid,
                                                              profile=profile)
                if not temp_ret:
                    ret['result'] = False
                    msg = 'Error attempting to set tags.'
                    ret['comment'] = ' '.join([ret['comment'], msg])
                    return ret
                if 'old' not in ret['changes']:
                    ret['changes'] = dictupdate.update(ret['changes'], {'old': {'tags': {}}})
                if 'new' not in ret['changes']:
                    ret['changes'] = dictupdate.update(ret['changes'], {'new': {'tags': {}}})
                for tag in all_tag_changes:
                    ret['changes']['new']['tags'][tag] = tags[tag]
                    if 'tags' in sg:
                        if sg['tags']:
                            if tag in sg['tags']:
                                ret['changes']['old']['tags'][tag] = sg['tags'][tag]
        if not tags_to_update and not tags_to_remove and not tags_to_add:
            ret['comment'] = ' '.join([ret['comment'], 'Tags are already set.'])
    return ret
231550
public void setVpcPeeringConnectionIds(java.util.Collection<String> vpcPeeringConnectionIds) {
        if (vpcPeeringConnectionIds == null) {
            this.vpcPeeringConnectionIds = null;
            return;
        }

        this.vpcPeeringConnectionIds = new com.amazonaws.internal.SdkInternalList<String>(vpcPeeringConnectionIds);
    }
707772
def _find_usage_vpcs(self):
        """"""
        # overall number of VPCs
        vpcs = self.conn.describe_vpcs()
        self.limits['VPCs']._add_current_usage(
            len(vpcs['Vpcs']),
            aws_type='AWS::EC2::VPC'
        )
396070
def describe(name, region=None, key=None, keyid=None, profile=None):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    try:
        # Returns an object if stack exists else an exception
        r = conn.describe_stacks(name)
        if r:
            stack = r[0]
            log.debug('Found VPC: %s', stack.stack_id)
            keys = ('stack_id', 'description', 'stack_status', 'stack_status_reason', 'tags')

            ret = dict([(k, getattr(stack, k)) for k in keys if hasattr(stack, k)])
            o = getattr(stack, 'outputs')
            p = getattr(stack, 'parameters')
            outputs = {}
            parameters = {}
            for i in o:
                outputs[i.key] = i.value
            ret['outputs'] = outputs
            for j in p:
                parameters[j.key] = j.value
            ret['parameters'] = parameters

            return {'stack': ret}

        log.debug('Stack %s exists.', name)
        return True
    except BotoServerError as e:
        log.warning('Could not describe stack %s.\n%s', name, e)
        return False
1133323
function buildVpc(cidrBlock = '10.0.0.0/16', { name = 'VPC' } = {}) {
  return {
    [name]: {
      Type: 'AWS::EC2::VPC',
      Properties: {
        CidrBlock: cidrBlock,
        EnableDnsSupport: true,
        EnableDnsHostnames: true,
        InstanceTenancy: 'default',
        Tags: [
          {
            Key: 'Name',
            Value: {
              Ref: 'AWS::StackName',
            },
          },
        ],
      },
    },
  };
}
986320
def external_system_identifiers2marc(self, key, value):
    
    def _is_scheme_cernkey(id_, schema):
        return schema == 'CERNKEY'

    def _is_scheme_spires(id_, schema):
        return schema == 'SPIRES'

    result_035 = self.get('035', [])
    id_dict = self.get('id_dict', defaultdict(list))
    result_970 = self.get('970', [])

    values = force_list(value)
    for value in values:
        id_ = value.get('value')
        schema = value.get('schema')

        if _is_scheme_spires(id_, schema):
            result_970.append({
                'a': id_,
            })
        elif _is_scheme_cernkey(id_, schema):
            result_035.append({
                '9': 'CERNKEY',
                'z': id_,
            })
        else:
            id_dict[schema].append(id_)

    self['970'] = result_970
    self['id_dict'] = id_dict
    return result_035
935531
def _create_eni_if_necessary(interface, vm_):
    '''
    
    '''
    if 'NetworkInterfaceId' in interface and interface['NetworkInterfaceId'] is not None:
        return {'DeviceIndex': interface['DeviceIndex'],
                'NetworkInterfaceId': interface['NetworkInterfaceId']}

    params = {'Action': 'DescribeSubnets'}
    subnet_query = aws.query(params,
                             return_root=True,
                             location=get_location(vm_),
                             provider=get_provider(),
                             opts=__opts__,
                             sigver='4')

    if 'SecurityGroupId' not in interface and 'securitygroupname' in interface:
        interface['SecurityGroupId'] = _get_securitygroupname_id(interface['securitygroupname'])
    if 'SubnetId' not in interface and 'subnetname' in interface:
        interface['SubnetId'] = _get_subnetname_id(interface['subnetname'])

    subnet_id = _get_subnet_id_for_interface(subnet_query, interface)
    if not subnet_id:
        raise SaltCloudConfigError(
            'No such subnet <{0}>'.format(interface.get('SubnetId'))
        )
    params = {'SubnetId': subnet_id}

    for k in 'Description', 'PrivateIpAddress', 'SecondaryPrivateIpAddressCount':
        if k in interface:
            params[k] = interface[k]

    for k in 'PrivateIpAddresses', 'SecurityGroupId':
        if k in interface:
            params.update(_param_from_config(k, interface[k]))

    if 'AssociatePublicIpAddress' in interface:
        # Associating a public address in a VPC only works when the interface is not
        # created beforehand, but as a part of the machine creation request.
        for k in ('DeviceIndex', 'AssociatePublicIpAddress', 'NetworkInterfaceId'):
            if k in interface:
                params[k] = interface[k]
        params['DeleteOnTermination'] = interface.get('delete_interface_on_terminate', True)
        return params

    params['Action'] = 'CreateNetworkInterface'

    result = aws.query(params,
                       return_root=True,
                       location=get_location(vm_),
                       provider=get_provider(),
                       opts=__opts__,
                       sigver='4')

    eni_desc = result[1]
    if not eni_desc or not eni_desc.get('networkInterfaceId'):
        raise SaltCloudException('Failed to create interface: {0}'.format(result))

    eni_id = eni_desc.get('networkInterfaceId')
    log.debug(
        'Created network interface %s inst %s',
        eni_id, interface['DeviceIndex']
    )

    associate_public_ip = interface.get('AssociatePublicIpAddress', False)
    if isinstance(associate_public_ip, six.string_types):
        # Assume id of EIP as value
        _associate_eip_with_interface(eni_id, associate_public_ip, vm_=vm_)

    if interface.get('associate_eip'):
        _associate_eip_with_interface(eni_id, interface.get('associate_eip'), vm_=vm_)
    elif interface.get('allocate_new_eip'):
        _new_eip = _request_eip(interface, vm_)
        _associate_eip_with_interface(eni_id, _new_eip, vm_=vm_)
    elif interface.get('allocate_new_eips'):
        addr_list = _list_interface_private_addrs(eni_desc)
        eip_list = []
        for idx, addr in enumerate(addr_list):
            eip_list.append(_request_eip(interface, vm_))
        for idx, addr in enumerate(addr_list):
            _associate_eip_with_interface(eni_id, eip_list[idx], addr, vm_=vm_)

    if 'Name' in interface:
        tag_params = {'Action': 'CreateTags',
                      'ResourceId.0': eni_id,
                      'Tag.0.Key': 'Name',
                      'Tag.0.Value': interface['Name']}
        tag_response = aws.query(tag_params,
                                 return_root=True,
                                 location=get_location(vm_),
                                 provider=get_provider(),
                                 opts=__opts__,
                                 sigver='4')
        if 'error' in tag_response:
            log.error('Failed to set name of interface {0}')

    return {'DeviceIndex': interface['DeviceIndex'],
            'NetworkInterfaceId': eni_id}
199943
def cli(env, identifier, no_vs, no_hardware):
    """"""

    mgr = SoftLayer.NetworkManager(env.client)
    subnet_id = helpers.resolve_id(mgr.resolve_subnet_ids, identifier,
                                   name='subnet')
    subnet = mgr.get_subnet(subnet_id)

    table = formatting.KeyValueTable(['name', 'value'])
    table.align['name'] = 'r'
    table.align['value'] = 'l'

    table.add_row(['id', subnet['id']])
    table.add_row(['identifier',
                   '%s/%s' % (subnet['networkIdentifier'],
                              str(subnet['cidr']))])
    table.add_row(['subnet type', subnet['subnetType']])
    table.add_row(['network space',
                   utils.lookup(subnet, 'networkVlan', 'networkSpace')])
    table.add_row(['gateway', subnet.get('gateway', formatting.blank())])
    table.add_row(['broadcast',
                   subnet.get('broadcastAddress', formatting.blank())])
    table.add_row(['datacenter', subnet['datacenter']['name']])
    table.add_row(['usable ips',
                   subnet.get('usableIpAddressCount', formatting.blank())])

    if not no_vs:
        if subnet['virtualGuests']:
            vs_table = formatting.Table(['hostname', 'domain', 'public_ip', 'private_ip'])
            for vsi in subnet['virtualGuests']:
                vs_table.add_row([vsi['hostname'],
                                  vsi['domain'],
                                  vsi.get('primaryIpAddress'),
                                  vsi.get('primaryBackendIpAddress')])
            table.add_row(['vs', vs_table])
        else:
            table.add_row(['vs', 'none'])

    if not no_hardware:
        if subnet['hardware']:
            hw_table = formatting.Table(['hostname', 'domain', 'public_ip', 'private_ip'])
            for hardware in subnet['hardware']:
                hw_table.add_row([hardware['hostname'],
                                  hardware['domain'],
                                  hardware.get('primaryIpAddress'),
                                  hardware.get('primaryBackendIpAddress')])
            table.add_row(['hardware', hw_table])
        else:
            table.add_row(['hardware', 'none'])

    env.fout(table)