projectIdFromMetadataServer function

Future<String> projectIdFromMetadataServer()

Returns a Future that completes with the Project ID for the current Google Cloud Project by checking project metadata.

If the metadata server cannot be contacted, a BadConfigurationException is thrown.

Implementation

Future<String> projectIdFromMetadataServer() async {
  const host = 'http://metadata.google.internal/';
  final url = Uri.parse('$host/computeMetadata/v1/project/project-id');

  try {
    final response = await http.get(
      url,
      headers: {'Metadata-Flavor': 'Google'},
    );

    if (response.statusCode != 200) {
      throw HttpException(
        '${response.body} (${response.statusCode})',
        uri: url,
      );
    }

    return response.body;
  } on SocketException catch (e) {
    throw BadConfigurationException(
      '''
Could not connect to $host.
If not running on Google Cloud, one of these environment variables must be set
to the target Google Project ID:
${gcpProjectIdEnvironmentVariables.join('\n')}
''',
      details: e.toString(),
    );
  }
}