Print key from a running instance's metadata
173423
def awsReadInstanceTag():
  """"""
  parser = argparse.ArgumentParser()

  parser.add_argument("--tag",
                      dest="tag",
                      required=True,
                      help="Which instance tag to read")

  cli = parser.parse_args()
  print haze.ec2.readMyEC2Tag(tagName=cli.tag)
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)
136008
def run_metadata_impl(self, run, tag):
    """"""
    try:
      run_metadata = self._multiplexer.RunMetadata(run, tag)
    except ValueError:
      # TODO(stephanwlee): Should include whether FE is fetching for v1 or v2 RunMetadata
      # so we can remove this try/except.
      tensor_events = self._multiplexer.Tensors(run, tag)
      if tensor_events is None:
        return None
      # Take the first event if there are multiple events written from different
      # steps.
      run_metadata = config_pb2.RunMetadata.FromString(
          tensor_events[0].tensor_proto.string_val[0])
    if run_metadata is None:
      return None
    return (str(run_metadata), 'text/x-protobuf')
234152
def _getMetadata(self, key):
        """"""
        if self.isClosed:
            raise ValueError("operation illegal for closed doc")

        return _fitz.Document__getMetadata(self, key)
1313412
def get_metadata(self, refresh=True):
        
        if refresh or not self._metadata:
            ident = self._id or self.name
            if not ident:
                raise ConuException(
                    "This container does not have a valid identifier.")
            out = run_cmd(["machinectl", "--no-pager", "show", ident], return_output=True, ignore_status=True)
            if "Could not get path to machine" in out:
                self._metadata = {}
            else:
                self._metadata = convert_kv_to_dict(out)
        return self._metadata
1333131
def repr_new_instance(self, class_data):
        
        classname = self.formatted_classname(class_data["classname"])
        instancename = self.formatted_instancename(class_data["classname"])
        arguments = list()
        for key, value in self.sorted_dict(class_data.get("metadata", dict())):
            arguments.append("%s=%r" % (key, value))
        return "%s = %s(%s)" % (
            instancename, classname, ", ".join(arguments))
648530
def _RunScript(self, metadata_key, metadata_script):
    
    process = subprocess.Popen(
        metadata_script, shell=True,
        executable=self.default_shell,
        stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
    while True:
      for line in iter(process.stdout.readline, b''):
        message = line.decode('utf-8', 'replace').rstrip('\n')
        if message:
          self.logger.info('%s: %s', metadata_key, message)
      if process.poll() is not None:
        break
    self.logger.info('%s: Return code %s.', metadata_key, process.returncode)
10298
def has_key(cls, *args):
        
        key = args if len(args) > 1 else args[0]
        return key in cls._instances
1190159
def get_metadata(self, key, counter_id):
        
        with self._lock:
            metadata = self._metadata[key]
            try:
                return metadata[counter_id]
            except KeyError:
                raise MetadataNotFoundError("No metadata for counter id '{}' found in the cache.".format(counter_id))
1179227
def _initialize_metadata_service(cls):
        
        if cls.inited:
            return

        instance_id = cls.get_attribute('instance/id')

        if instance_id is not None:
            cls.is_running = True

            _GCP_METADATA_MAP['instance_id'] = instance_id

            # fetch attributes from metadata request
            for attribute_key, attribute_uri in _GCE_ATTRIBUTES.items():
                if attribute_key not in _GCP_METADATA_MAP:
                    attribute_value = cls.get_attribute(attribute_uri)
                    if attribute_value is not None:  # pragma: NO COVER
                        _GCP_METADATA_MAP[attribute_key] = attribute_value

        cls.inited = True
1053447
def metadata(self):
        
        if self.__metadata__ is None:
            metadata = {}
            for test_run in self.test_runs.defer(None).all():
                for key, value in test_run.metadata.items():
                    metadata.setdefault(key, [])
                    if value not in metadata[key]:
                        metadata[key].append(value)
            for key in metadata.keys():
                if len(metadata[key]) == 1:
                    metadata[key] = metadata[key][0]
                else:
                    metadata[key] = sorted(metadata[key], key=str)
            self.__metadata__ = metadata
        return self.__metadata__
1155599
def get_from_human_key(self, key):
        """"""
        if key in self._identifier_map:
            return self._identifier_map[key]
        raise KeyError(key)
675177
def scanmeta(f):
    
    print(f)
    if isinstance(f, str):
        f = io.open(f, mode='r', encoding='latin-1')

    done = False

    l = f.readline()
    s = None
    while l and s is None:
        i = l.find('!')
        if i >= 0:
            l = l[i+1:]
            i = l.find('@meta')
            if i >= 0:
                l = l[i+5:]
                i = l.find('@endmeta')
                if i >= 0:
                    s = l[:i]
                    done = True
                else:
                    s = l
        l = f.readline()
    
    if not done and not l:
        return { }

    while l and not done:
        i = l.find('!')
        if i >= 0:
            l = l[i+1:]
            i = l.find('@endmeta')
            if i >= 0:
                s += ' '+l[:i]
                done = True
            else:
                s += ' '+l

        l = f.readline()

    s = map(lambda x: x.split(':'), s.split())
    d = { }
    for x in s:
        if len(x) > 2 or len(x) == 0:
            raise RuntimeError('Syntax error in meta information.')
        elif len(x) == 2:
            d[x[0]] = x[1]
        else:
            d[x[0]] = None

    return d
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
150228
def _get_key_id(alias, region=None, key=None, keyid=None, profile=None):
    '''
    
    '''
    key_metadata = describe_key(
        alias, region, key, keyid, profile
    )['key_metadata']
    return key_metadata['KeyId']
321470
def generated_key(key):
    """"""
    key_name = key['name']
    if key['method'] == 'uuid':
        LOG.debug("Setting %s to a uuid", key_name)
        return str(uuid4())
    elif key['method'] == 'words':
        LOG.debug("Setting %s to random words", key_name)
        return random_word()
    elif key['method'] == 'static':
        if 'value' not in key.keys():
            raise aomi.exceptions.AomiData("Missing static value")

        LOG.debug("Setting %s to a static value", key_name)
        return key['value']
    else:
        raise aomi.exceptions.AomiData("Unexpected generated secret method %s"
                                       % key['method'])
1082671
def from_metadata(cls, metadata: Dict[str, Any]) -> 'LogFields':
        
        return cls(fields=json.loads(metadata.get(LOG_FIELDS_KEY_META, '{}')))