Gets the VPC ID for this EC2 instance

    :return: String instance ID or None
162114
def get_vpc_id_from_mac_address():
    
    log = logging.getLogger(mod_logger + '.get_vpc_id')

    # Exit if not running on AWS
    if not is_aws():
        log.info('This machine is not running in AWS, exiting...')
        return

    # Get the primary interface MAC address to query the meta data service
    log.debug('Attempting to determine the primary interface MAC address...')
    try:
        mac_address = get_primary_mac_address()
    except AWSMetaDataError:
        _, ex, trace = sys.exc_info()
        msg = '{n}: Unable to determine the mac address, cannot determine VPC ID:\n{e}'.format(
            n=ex.__class__.__name__, e=str(ex))
        log.error(msg)
        return

    vpc_id_url = metadata_url + 'network/interfaces/macs/' + mac_address + '/vpc-id'
    try:
        response = urllib.urlopen(vpc_id_url)
    except(IOError, OSError) as ex:
        msg = 'Unable to query URL to get VPC ID: {u}\n{e}'.format(u=vpc_id_url, e=ex)
        log.error(msg)
        return

    # Check the code
    if response.getcode() != 200:
        msg = 'There was a problem querying url: {u}, returned code: {c}, unable to get the vpc-id'.format(
                u=vpc_id_url, c=response.getcode())
        log.error(msg)
        return
    vpc_id = response.read()
    return vpc_id
991284
def get_ips(self, instance_id):
        
        if not instance_id:
          raise InstanceError("could not retrieve the ip address for node: "
                              "no associated instance id")
        gce = self._connect()
        instances = gce.instances()
        try:
            request = instances.get(instance=instance_id,
                                    project=self._project_id, zone=self._zone)
            response = self._execute_request(request)
            ip_public = None

            # If the instance is in status TERMINATED, then there will be
            # no IP addresses.
            if response and response['status'] in ('STOPPING', 'TERMINATED'):
              log.info("node '%s' state is '%s'; no IP address(es)" %
                       (instance_id, response['status']))
              return [None]

            if response and "networkInterfaces" in response:
                interfaces = response['networkInterfaces']
                if interfaces:
                    if "accessConfigs" in interfaces[0]:
                        ip_public = interfaces[0]['accessConfigs'][0]['natIP']

            if ip_public:
                return [ip_public]
            else:
                raise InstanceError("could not retrieve the ip address for "
                                    "node `%s`, please check the node "
                                    "through the cloud provider interface"
                                    % instance_id)

        except (HttpError, CloudProviderError) as e:
            raise InstanceError('could not retrieve the ip address of `%s`: '
                                '`%s`' % (instance_id, e))
568212
def set_vm_id
      @vm_id ||= fetch_gce_metadata('instance/id') if @platform == Platform::GCE
      @vm_id ||= ec2_metadata['instanceId'] if @platform == Platform::EC2
    rescue StandardError => e
      @log.error 'Failed to obtain vm_id: ', error: e
    end
462892
def parse_instance(self, global_params, region, reservation):
        
        for i in reservation['Instances']:
            instance = {}
            vpc_id = i['VpcId'] if 'VpcId' in i and i['VpcId'] else ec2_classic
            manage_dictionary(self.vpcs, vpc_id, VPCConfig(self.vpc_resource_types))
            instance['reservation_id'] = reservation['ReservationId']
            instance['id'] = i['InstanceId']
            get_name(i, instance, 'InstanceId')
            get_keys(i, instance, ['KeyName', 'LaunchTime', 'InstanceType', 'State', 'IamInstanceProfile', 'SubnetId'])
            # Network interfaces & security groups
            manage_dictionary(instance, 'network_interfaces', {})
            for eni in i['NetworkInterfaces']:
                nic = {}
                get_keys(eni, nic, ['Association', 'Groups', 'PrivateIpAddresses', 'SubnetId', 'Ipv6Addresses'])
                instance['network_interfaces'][eni['NetworkInterfaceId']] = nic
            self.vpcs[vpc_id].instances[i['InstanceId']] = instance
25233
def get_provider(vm_=None):
    '''
    
    '''
    if vm_ is None:
        provider = __active_provider_name__ or 'ec2'
    else:
        provider = vm_.get('provider', 'ec2')

    if ':' in provider:
        prov_comps = provider.split(':')
        provider = prov_comps[0]
    return provider
1016603
def to_vars_dict(self):
        
        return {
            'aws_access_key_id':      self._access_key,
            'aws_secret_access_key':  self._secret_key,
            'aws_region':             self._region_name,
            'aws_vpc_name':           (self._vpc or ''),
            'aws_vpc_id':             (self._vpc_id or ''),
        }
1241457
def get_ec2_info(instance_id,
                 region,
                 access_key_id,
                 secret_access_key,
                 username):
    
    conn = connect_to_ec2(region, access_key_id, secret_access_key)
    instance = conn.get_only_instances(
        filters={'instance_id': instance_id}
        )[0]

    data = {}
    data['public_dns_name'] = instance.public_dns_name
    data['id'] = instance.id
    data['instance_type'] = instance.instance_type
    data['ip_address'] = instance.ip_address
    data['architecture'] = instance.architecture
    data['state'] = instance.state
    data['region'] = region
    data['cloud_type'] = 'ec2'
    data['username'] = username

    # find out the distribution running on the instance
    if username is not None:
        wait_for_ssh(data['ip_address'])
        with settings(host_string=username + '@' + data['ip_address']):
            data['distribution'] = linux_distribution(username,
                                                      data['ip_address'])
            data['os_release'] = os_release(username,
                                            data['ip_address'])

    try:
        volume = conn.get_all_volumes(
            filters={'attachment.instance-id': instance.id})[0].id
        data['volume'] = volume
    except:
        data['volume'] = ''
    return data
305805
def _get_instance(self):
        """"""
        try:
            instance = self.compute_driver.ex_get_node(
                self.running_instance_id,
                zone=self.region
            )
        except ResourceNotFoundError as e:
            raise GCECloudException(
                'Instance with id: {id} cannot be found: {error}'.format(
                    id=self.running_instance_id, error=e
                )
            )

        return instance
852510
def get_vcenter_vm_uuid_by_name(host, user, password, vm_name):
    
    vc = VcenterInterface(host, user, password)
    vmi = VmInterface(vc, vm_name)
    return vmi.get_instance_uuid()
777697
public static String getPrivateIp(InstanceInfo instanceInfo) {
        String defaultPrivateIp = null;
        if (instanceInfo.getDataCenterInfo() instanceof AmazonInfo) {
            defaultPrivateIp = ((AmazonInfo) instanceInfo.getDataCenterInfo()).get(AmazonInfo.MetaDataKey.localIpv4);
        }

        if (isNullOrEmpty(defaultPrivateIp)) {
            // no other information, best effort
            defaultPrivateIp = instanceInfo.getIPAddr();
        }

        return defaultPrivateIp;
    }
348628
def read_creds_from_ec2_instance_metadata():
    
    creds = init_creds()
    try:
        has_role = requests.get('http://169.254.169.254/latest/meta-data/iam/security-credentials', timeout = 1)
        if has_role.status_code == 200:
            iam_role = has_role.text
            credentials = requests.get('http://169.254.169.254/latest/meta-data/iam/security-credentials/%s/' %
                                       iam_role.strip()).json()
            for c in ['AccessKeyId', 'SecretAccessKey']:
                creds[c] = credentials[c]
            creds['SessionToken'] = credentials['Token']
        return creds
    except Exception as e:
        return False
1271253
def get_ips(self, instance_id):
        
        self._load_instance(instance_id)
        instance = self._load_instance(instance_id)
        IPs = [ip for ip in (instance.private_ip_address, instance.ip_address) if ip]

        # We also need to check if there is any floating IP associated
        if self.request_floating_ip and not self._vpc:
            # We need to list the floating IPs for this instance
            floating_ips = [ip for ip in self._ec2_connection.get_all_addresses() if ip.instance_id == instance.id]
            if not floating_ips:
                log.debug("Public ip address has to be assigned through "
                          "elasticluster.")
                ip = self._allocate_address(instance)
                # This is probably the preferred IP we want to use
                IPs.insert(0, ip)
            else:
                IPs = [ip.public_ip for ip in floating_ips] + IPs

        return list(set(IPs))
648789
def get_name(tags_or_instance_or_id):
  

  ec2 = get_ec2_resource()
  if hasattr(tags_or_instance_or_id, 'tags'):
    tags = tags_or_instance_or_id.tags
  elif isinstance(tags_or_instance_or_id, str):
    tags = ec2.Instance(tags_or_instance_or_id).tags
  elif tags_or_instance_or_id is None:
    return EMPTY_NAME
  else:
    assert isinstance(tags_or_instance_or_id,
                      Iterable), "expected iterable of tags"
    tags = tags_or_instance_or_id

  if not tags:
    return EMPTY_NAME
  names = [entry['Value'] for entry in tags if entry['Key'] == 'Name']
  if not names:
    return ''
  if len(names) > 1:
    assert False, "have more than one name: " + str(names)
  return names[0]
806204
def get_access_id(self):
        
        access_id = self.get_as_nullable_string("access_id")
        access_id = access_id if access_id != None else self.get_as_nullable_string("client_id")
        return access_id
76719
def print_ec2_info(region,
                   instance_id,
                   access_key_id,
                   secret_access_key,
                   username):
    
    data = get_ec2_info(instance_id=instance_id,
                        region=region,
                        access_key_id=access_key_id,
                        secret_access_key=secret_access_key,
                        username=username)

    log_green("region: %s" % data['region'])
    log_green("Instance_type: %s" % data['instance_type'])
    log_green("Instance state: %s" % data['state'])
    log_green("Public dns: %s" % data['public_dns_name'])
    log_green("Ip address: %s" % data['ip_address'])
    log_green("volume: %s" % data['volume'])
    log_green("user: %s" % data['username'])
    log_green("ssh -i %s %s@%s" % (env.key_filename,
                                   username,
                                   data['ip_address']))
791480
def _get_ids_from_hostname(self, hostname):
        """"""
        results = self.list_instances(hostname=hostname, mask="id")
        return [result['id'] for result in results]
1165430
def get_id(name=None, cidr=None, tags=None, region=None, key=None, keyid=None,
           profile=None):
    '''
    

    '''

    try:
        return {'id': _get_id(vpc_name=name, cidr=cidr, tags=tags, region=region,
                              key=key, keyid=keyid, profile=profile)}
    except BotoServerError as e:
        return {'error': __utils__['boto.get_error'](e)}