getMetadataValue function

Future<String> getMetadataValue(
  1. String path, {
  2. Client? client,
  3. Duration timeout = const Duration(seconds: 3),
  4. bool refresh = false,
})

Retrieves a value from the GCE metadata server.

The path represents the specific metadata endpoint to query (e.g., project/project-id or instance/service-accounts/default/email).

The result is cached for the lifetime of the Dart process. Subsequent calls return the cached value without performing discovery again.

If client is provided, it is used to make the request to the metadata server.

If refresh is true, the cache is cleared and the value is re-computed.

If the metadata server cannot be contacted or returns a non-200 status code, a MetadataServerException is thrown.

Implementation

Future<String> getMetadataValue(
  String path, {
  http.Client? client,
  Duration timeout = const Duration(seconds: 3),
  bool refresh = false,
}) async {
  if (refresh) {
    _metadataCache.remove(path);
  } else {
    if (_metadataCache[path] case final value?) return value;
  }

  final value = await fetchMetadataValue(
    path,
    client: client,
    timeout: timeout,
  );
  return _metadataCache[path] = value;
}