Reputation: 507
Jumping right to it...
I have the following python code in a Google Cloud Function
main.py
import flask, requests
def gce_test(request):
test = {"data": {}, "meta": {}, "error": {}}
metadata_server = "http://metadata/computeMetadata/v1/instance/"
metadata_flavor = {'Metadata-Flavor' : 'Google'}
gce_id = requests.get(metadata_server + 'id', headers = metadata_flavor).text
gce_name = requests.get(metadata_server + 'hostname', headers = metadata_flavor).text
gce_machine_type = requests.get(metadata_server + 'machine-type', headers = metadata_flavor).text
test["data"]["gce_id"] = gce_id
test["data"]["gce_name"] = gce_name
test["data"]["gce_machine_type"] = gce_machine_type
test["meta"]["metadata_server"] = metadata_server
test["meta"]["metadata_flavor"] = metadata_flavor
test["meta"]["metadata_server_full"] = metadata_server + 'id'
test["meta"]['generator'] = 'google-cloud-function'
return flask.jsonify(test)
The problem that I am facing is I get a 404 page not found
for gce_id, gce_machine_type, gce_name which means the request to the metadata_server is not being made...
My question is how do I make a HTTP Get request to the metadata_server and pass it the instance name as a param...is that doable?
Upvotes: 1
Views: 867
Reputation: 916
You're currently making requests to the GCE metadata server URL. Cloud Functions run on top of GAE Standard, and as such end up using the http://metadata.google.internal url. I've provided an example that works with the current cloud function to log the project id.
import flask, requests
def gce_test(request):
test = {"data": {}, "meta": {}, "error": {}}
metadata_server = "http://metadata.google.internal/computeMetadata/v1/project/project-id"
metadata_flavor = {'Metadata-Flavor' : 'Google'}
project = requests.get(metadata_server, headers = metadata_flavor).text
test["data"]["gce_id"] = project
return flask.jsonify(test)
Upvotes: 2