Sander van den Oord
Sander van den Oord

Reputation: 12808

Which ip address triggered my HTTP Cloud Function?

I would like to see which IP address triggered my HTTP triggered Cloud Function.

This is the (demo code) of my python cloud function:

def hello_world(request):
    request_json = request.get_json()
    if request.args and 'message' in request.args:
        return request.args.get('message')
    elif request_json and 'message' in request_json:
        return request_json['message']
    else:
        return f'Hello World!'

Upvotes: 1

Views: 713

Answers (1)

Sander van den Oord
Sander van den Oord

Reputation: 12808

Since Python Cloud Functions on GCP are using Flask you can add the following to your code:

# get ip address for logging purposes 
if request.environ.get('HTTP_X_FORWARDED_FOR') is None:
    print(f"IP address: {request.environ['REMOTE_ADDR']}")
else:
    print(f"IP address: {request.environ['HTTP_X_FORWARDED_FOR']}") # if behind a proxy

See also: Get IP address of visitors using Flask for Python

Print statements get sent to Cloud Logging, so the ip address will be visible in the logging.
To find your ip address log entry faster you can filter in Cloud Logging with:
resource.labels.function_name="name_of_your_cloud_function"

Above answer is for 1st generation Cloud Functions.
When using 2nd generation Cloud Functions you don't need to add specific code to check the ip address of the function caller.
You can just check Cloud Logging and filter on:
resource.type="cloud_run_revision"

Upvotes: 3

Related Questions