Accessing computeMetadata when debugging in Cloud Code

1.1k Views Asked by At

I'm trying to debug a Cloud Run container locally. In my code I'm trying to retrieve information about the environment to through computeMetadata.

    location = requests.get("http://metadata.google.internal/computeMetadata/v1/instance/region",
                          headers={'Metadata-Flavor': 'Google'}).text
    logging.warning(f"Location set to {location}")
    project = requests.get("http://metadata.google.internal/computeMetadata/v1/project/project-id",
                              headers={'Metadata-Flavor': 'Google'}).text
    logging.warning(f"Project set to {project}")

When executing this piece of code I get the below error.

urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='metadata.google.internal', port=80): Max retries exceeded with url: /computeMetadata/v1/instance/region (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fb00be99190>: Failed to establish a new connection: [Errno 111] Connection refused'))

Of course there is nothing that I'm aware of running on port 80 on my Macbook that would serve this up, and there doesn't appear to be anything in the container that would either, so it would make sense that its unable to connect.

So with that said, how can I execute this code locally to make sure it behaves as I want it to before deploying it? For the time being I have wrapped it in a try/except statement - but its not ideal for replicating real world scenarios.

1

There are 1 best solutions below

0
On BEST ANSWER

There are several emulators out there that you can run locally.

Guillaume pointed out in question comments one which has had more GCE focus

And more recently Kelsey Hightower has released one more focused on metadata available in Cloud Run