Try fetching instance metadata at 'curl http://169.254.169.254/latest/meta-data/'
    to see if host is on an ec2 instance
13469
def is_ec2_instance():
    """"""

    # Note: this code assumes that docker containers running on ec2 instances
    # inherit instances metadata, which they do as of 2016-08-25

    global IS_EC2_INSTANCE

    if IS_EC2_INSTANCE != -1:
        # Returned the cached value
        return IS_EC2_INSTANCE

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(0.2)
    try:
        s.connect(("169.254.169.254", 80))
        IS_EC2_INSTANCE = 1
        return True
    except socket.timeout:
        IS_EC2_INSTANCE = 0
        return False
    except socket.error:
        IS_EC2_INSTANCE = 0
        return False
1291859
def http_get_instance_env():
  
  try:
    info = json.loads(http_get_metadata('iam/info'))
  except Exception as error:
    raise IOError("Error looking up metadata:iam/info: " + repr(error))
  return info["InstanceProfileArn"].split(":")[5].split("/")[1].split("-",1)[0]
985671
def getMetadata(self, remote, address, key):
        """"""
        if self._server is not None:
            # pylint: disable=E1121
            return self._server.getAllMetadata(remote, address, key)
1090371
function _fetchHostMeta(host, callback) {
	var url = "http://" + host + "/.well-known/host-meta";
	console.log("Requesting host meta at " + url);
   	Http.get(url, function(err, response, content) {
		if (err) return callback(err);
		if (response.statusCode == 200) {
			try {
			    callback(null, _parseHostMeta(content));
			} catch (e) {
			    callback(e);
			}
   		} else {
   			callback(new Error("Fetching host meta returned HTTP Status " + response.statusCode));
   		}
    });
}
662375
def _get_real_instance_if_mismatch(vpc_info, ipaddr, instance, eni):
    
    # Careful! A route may be a black-hole route, which still has instance and
    # ENI information for an instance that doesn't exist anymore. If a host was
    # terminated and a new host got the same IP then this route won't be
    # updated and will keep pointing to a non-existing node. So we find the
    # instance by IP and check that the route really points to this instance.
    inst_id = instance.id if instance else ""
    eni_id  = eni.id if eni else ""
    if ipaddr:
        real_instance, real_eni = \
                        find_instance_and_eni_by_ip(vpc_info, ipaddr)
        if real_instance.id != inst_id  or real_eni.id != eni_id:
            return real_instance
    return None
100881
def get_instances(name, lifecycle_state="InService", health_status="Healthy",
                  attribute="private_ip_address", attributes=None, region=None,
                  key=None, keyid=None, profile=None):
    '''
    

    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
    ec2_conn = _get_ec2_conn(region=region, key=key, keyid=keyid, profile=profile)
    retries = 30
    while True:
        try:
            asgs = conn.get_all_groups(names=[name])
            break
        except boto.exception.BotoServerError as e:
            if retries and e.code == 'Throttling':
                log.debug('Throttled by AWS API, retrying in 5 seconds...')
                time.sleep(5)
                retries -= 1
                continue
            log.error(e)
            return False
    if len(asgs) != 1:
        log.debug("name '%s' returns multiple ASGs: %s", name, [asg.name for asg in asgs])
        return False
    asg = asgs[0]
    instance_ids = []
    # match lifecycle_state and health_status
    for i in asg.instances:
        if lifecycle_state is not None and i.lifecycle_state != lifecycle_state:
            continue
        if health_status is not None and i.health_status != health_status:
            continue
        instance_ids.append(i.instance_id)
    # get full instance info, so that we can return the attribute
    instances = ec2_conn.get_only_instances(instance_ids=instance_ids)
    if attributes:
        return [[_convert_attribute(instance, attr) for attr in attributes] for instance in instances]
    else:
        # properly handle case when not all instances have the requested attribute
        return [_convert_attribute(instance, attribute) for instance in instances if getattr(instance, attribute)]
1259149
def awsReadMetadataKey():
  """"""
  parser = argparse.ArgumentParser()

  parser.add_argument("--key",
                      dest="keyname",
                      help="Which metadata key to read")

  cli = parser.parse_args()

  print getMetadataKey(name=cli.keyname)
1343651
def show_instance(name, call=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The show_instance action must be called with '
            '-a or --action.'
        )

    vm_properties = [
        "config.hardware.device",
        "summary.storage.committed",
        "summary.storage.uncommitted",
        "summary.storage.unshared",
        "layoutEx.file",
        "config.guestFullName",
        "config.guestId",
        "guest.net",
        "config.hardware.memoryMB",
        "name",
        "config.hardware.numCPU",
        "config.files.vmPathName",
        "summary.runtime.powerState",
        "guest.toolsStatus"
    ]

    vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)

    for vm in vm_list:
        if vm['name'] == name:
            return _format_instance_info(vm)

    return {}
311133
def _extract_instance_info(instances):
    '''
    
    '''
    ret = {}
    for instance in instances:
        # items could be type dict or list (for stopped EC2 instances)
        if isinstance(instance['instancesSet']['item'], list):
            for item in instance['instancesSet']['item']:
                name = _extract_name_tag(item)
                ret[name] = item
                ret[name]['name'] = name
                ret[name].update(
                    dict(
                        id=item['instanceId'],
                        image=item['imageId'],
                        size=item['instanceType'],
                        state=item['instanceState']['name'],
                        private_ips=item.get('privateIpAddress', []),
                        public_ips=item.get('ipAddress', [])
                    )
                )
        else:
            item = instance['instancesSet']['item']
            name = _extract_name_tag(item)
            ret[name] = item
            ret[name]['name'] = name
            ret[name].update(
                dict(
                    id=item['instanceId'],
                    image=item['imageId'],
                    size=item['instanceType'],
                    state=item['instanceState']['name'],
                    private_ips=item.get('privateIpAddress', []),
                    public_ips=item.get('ipAddress', [])
                )
            )

    return ret
1008353
def check_correct_host(self):
        
        if self._host == 'knoema.com':
            return
        url = self._get_url('/api/1.0/frontend/tags')
        req = urllib.request.Request(url)
        try:
            resp = urllib.request.urlopen(req)
        except:
            raise ValueError('The specified host {} does not exist'.format(self._host))
220046
def show_instance(name, call=None):
    '''
    
    '''
    response = _query('grid', 'server/get', args={'name': name})
    ret = {}
    for item in response['list']:
        name = item['name']
        ret[name] = item

        ret[name]['image_info'] = item['image']
        ret[name]['image'] = item['image']['friendlyName']
        ret[name]['size'] = item['ram']['name']
        ret[name]['public_ips'] = [item['ip']['ip']]
        ret[name]['private_ips'] = []
        ret[name]['state_info'] = item['state']
        if 'active' in item['state']['description']:
            ret[name]['state'] = 'RUNNING'
    return ret
268740
private static void retrieveServerMetadata() throws Exception {
        if (get() == null) {
            throw new IllegalStateException("Cannot retrieve the server metadata - no reference to Chameleon stored " +
                    "in the holder");
        }

        int factor = Integer.getInteger("time.factor", 1);
        if (factor != 1) {
            TimeUtils.TIME_FACTOR = factor;
        }

        // Before checking, ensure stability.
        ServiceReference[] references = get().waitForStability().context().getAllServiceReferences(WisdomEngine.class
                .getName(), null);

        if (references == null || references.length == 0) {
            references = get().waitForStability().context().getAllServiceReferences(WisdomEngine.class.getName(), null);
        }

        if (references == null || references.length == 0) {
            throw new IllegalStateException("Cannot retrieve the Wisdom Engine service");
        }

        Object engine = get().context().getService(references[0]);
        HOST_NAME = (String) engine.getClass().getMethod("hostname").invoke(engine);
        HTTP_PORT = (int) engine.getClass().getMethod("httpPort").invoke(engine);
        HTTPS_PORT = (int) engine.getClass().getMethod("httpsPort").invoke(engine);
    }
1342698
def is_virtual_host(endpoint_url, bucket_name):
    
    is_valid_bucket_name(bucket_name)

    parsed_url = urlsplit(endpoint_url)
    # bucket_name can be valid but '.' in the hostname will fail
    # SSL certificate validation. So do not use host-style for
    # such buckets.
    if 'https' in parsed_url.scheme and '.' in bucket_name:
        return False
    for host in ['s3.amazonaws.com', 'aliyuncs.com']:
        if host in parsed_url.netloc:
            return True
    return False
960795
def request_instance(vm_):
    '''
    
    '''
    if not GCE_VM_NAME_REGEX.match(vm_['name']):
        raise SaltCloudSystemExit(
            'VM names must start with a letter, only contain letters, numbers, or dashes '
            'and cannot end in a dash.'
        )

    try:
        # Check for required profile parameters before sending any API calls.
        if vm_['profile'] and config.is_profile_configured(__opts__,
                                                           __active_provider_name__ or 'gce',
                                                           vm_['profile'],
                                                           vm_=vm_) is False:
            return False
    except AttributeError:
        pass

    __utils__['cloud.fire_event'](
        'event',
        'create instance',
        'salt/cloud/{0}/creating'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    conn = get_conn()

    kwargs = {
        'name': vm_['name'],
        'size': __get_size(conn, vm_),
        'image': __get_image(conn, vm_),
        'location': __get_location(conn, vm_),
        'ex_network': __get_network(conn, vm_),
        'ex_subnetwork': __get_subnetwork(vm_),
        'ex_tags': __get_tags(vm_),
        'ex_metadata': __get_metadata(vm_),
    }
    external_ip = config.get_cloud_config_value(
        'external_ip', vm_, __opts__, default='ephemeral'
    )

    if external_ip.lower() == 'ephemeral':
        external_ip = 'ephemeral'
        vm_['external_ip'] = external_ip
    elif external_ip == 'None':
        external_ip = None
        vm_['external_ip'] = external_ip
    else:
        region = __get_region(conn, vm_)
        external_ip = __create_orget_address(conn, external_ip, region)
        vm_['external_ip'] = {
            'name': external_ip.name,
            'address': external_ip.address,
            'region': external_ip.region.name
        }
    kwargs['external_ip'] = external_ip

    if LIBCLOUD_VERSION_INFO > (0, 15, 1):

        kwargs.update({
            'ex_disk_type': config.get_cloud_config_value(
                'ex_disk_type', vm_, __opts__, default='pd-standard'),
            'ex_disk_auto_delete': config.get_cloud_config_value(
                'ex_disk_auto_delete', vm_, __opts__, default=True),
            'ex_disks_gce_struct': config.get_cloud_config_value(
                'ex_disks_gce_struct', vm_, __opts__, default=None),
            'ex_service_accounts': config.get_cloud_config_value(
                'ex_service_accounts', vm_, __opts__, default=None),
            'ex_can_ip_forward': config.get_cloud_config_value(
                'ip_forwarding', vm_, __opts__, default=False),
            'ex_preemptible': config.get_cloud_config_value(
                'preemptible', vm_, __opts__, default=False)
        })
        if kwargs.get('ex_disk_type') not in ('pd-standard', 'pd-ssd'):
            raise SaltCloudSystemExit(
                'The value of \'ex_disk_type\' needs to be one of: '
                '\'pd-standard\', \'pd-ssd\''
            )

    # GCE accelerator options are only supported as of libcloud >= 2.3.0
    # and Python 3+ is required so that libcloud will detect a type of
    # 'string' rather than 'unicode'
    if LIBCLOUD_VERSION_INFO >= (2, 3, 0) and isinstance(u'test', str):

        kwargs.update({
            'ex_accelerator_type': config.get_cloud_config_value(
                'ex_accelerator_type', vm_, __opts__, default=None),
            'ex_accelerator_count': config.get_cloud_config_value(
                'ex_accelerator_count', vm_, __opts__, default=None)
        })
        if kwargs.get('ex_accelerator_type'):
            log.warning(
                'An accelerator is being attached to this instance, '
                'the ex_on_host_maintenance setting is being set to '
                '\'TERMINATE\' as a result'
            )
            kwargs.update({
                'ex_on_host_maintenance': 'TERMINATE'
            })

    log.info(
        'Creating GCE instance %s in %s',
        vm_['name'], kwargs['location'].name
    )
    log.debug('Create instance kwargs %s', kwargs)

    __utils__['cloud.fire_event'](
        'event',
        'requesting instance',
        'salt/cloud/{0}/requesting'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('requesting', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    try:
        node_data = conn.create_node(**kwargs)
    except Exception as exc:  # pylint: disable=W0703
        log.error(
            'Error creating %s on GCE\n\n'
            'The following exception was thrown by libcloud when trying to '
            'run the initial deployment: \n%s',
            vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
        )
        return False

    volumes = config.get_cloud_config_value(
        'volumes', vm_, __opts__, search_global=True
    )

    if volumes:
        __utils__['cloud.fire_event'](
            'event',
            'attaching volumes',
            'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
            args={'volumes': volumes},
            sock_dir=__opts__['sock_dir'],
            transport=__opts__['transport']
        )

        log.info('Create and attach volumes to node %s', vm_['name'])
        create_attach_volumes(
            vm_['name'],
            {
                'volumes': volumes,
                'node': node_data
            },
            call='action'
        )

    try:
        node_dict = show_instance(node_data['name'], 'action')
    except TypeError:
        # node_data is a libcloud Node which is unsubscriptable
        node_dict = show_instance(node_data.name, 'action')

    return node_dict, node_data
931833
def check(self, instance):
        
        # Connection information
        host = instance.get('host', "localhost")
        namespace = instance.get('namespace', "root\\cimv2")
        provider = instance.get('provider')
        username = instance.get('username', "")
        password = instance.get('password', "")

        # WMI instance
        wmi_class = instance.get('class')
        metrics = instance.get('metrics')
        filters = instance.get('filters')
        tag_by = instance.get('tag_by', "")
        tag_queries = instance.get('tag_queries', [])

        constant_tags = instance.get('constant_tags')
        custom_tags = instance.get('tags', [])
        if constant_tags is None:
            constant_tags = list(custom_tags)
        else:
            constant_tags.extend(custom_tags)
            self.log.warning("`constant_tags` is being deprecated, please use `tags`")

        # Create or retrieve an existing WMISampler
        instance_hash = hash_mutable(instance)
        instance_key = self._get_instance_key(host, namespace, wmi_class, instance_hash)

        metric_name_and_type_by_property, properties = self._get_wmi_properties(instance_key, metrics, tag_queries)

        wmi_sampler = self._get_wmi_sampler(
            instance_key,
            wmi_class,
            properties,
            tag_by=tag_by,
            filters=filters,
            host=host,
            namespace=namespace,
            provider=provider,
            username=username,
            password=password,
        )

        # Sample, extract & submit metrics
        try:
            wmi_sampler.sample()
            metrics = self._extract_metrics(wmi_sampler, tag_by, tag_queries, constant_tags)
        except TimeoutException:
            self.log.warning(
                u"WMI query timed out."
                u" class={wmi_class} - properties={wmi_properties} -"
                u" filters={filters} - tag_queries={tag_queries}".format(
                    wmi_class=wmi_class, wmi_properties=properties, filters=filters, tag_queries=tag_queries
                )
            )
        else:
            self._submit_metrics(metrics, metric_name_and_type_by_property)
1267478
def wait_for_instance(instance):
    

    status = None
    print("getting status for instance {} ...".format(instance.id))
    while status is None:
        try:
            status = instance.update()
            if status is None:
                time.sleep(2)
        except EC2ResponseError:
            time.sleep(2)

    print("waiting for instance {} ...".format(instance.id))

    while status == "pending":
        time.sleep(2)
        status = instance.update()

    if status != "running":
        print("Invalid status when starting instance {}: {}".format(instance.id, status))
        return False

    print("New instance {} started: {}".format(instance.id, instance.ip_address))
    return True
1013162
def show_instance(name, call=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The show_instance action must be called with -a or --action.'
        )

    conn = get_conn()
    node = conn.show_instance(name).__dict__
    __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)
    return node