Monday, March 9, 2020

AWS Lambda Python url request

Web call in Lambda Python 

...without using requests from botocore.vendored module


Recently, it became not possible to use request module from botocore.vendored. So here is a workaround and a handy little ditty to test your network configuration from inside your Lambda function.

I use a Lambda variable called 'hostname'


import json
import socket
import os
import urllib.request


def lambda_handler(event, context):
    # TODO implement
    ABOUTME = socket.gethostname()    
    MYIP = socket.gethostbyname(ABOUTME)   
    print("About me...")
    print(ABOUTME, "=>", MYIP)
    
    print("Check outside connection...")
    HOSTNAME = os.environ['hostname']
    IP = socket.gethostbyname(HOSTNAME)
    print(HOSTNAME, "=>",IP)
    
    URL = "https://api.ipify.org?format=json"
    req = urllib.request.Request(URL)
    response = urllib.request.urlopen(req)
    output = response.read().decode('utf8')
    fromOutsideIP = json.loads(output)["ip"]
    print('Your advertised source IP is',fromOutsideIP)
    
    return {
        'statusCode': 200,
        'body': ('Done')
    }

No comments:

Post a Comment

AWS WAF log4j query

How to query AWS WAF log for log4j attacks 1. Setup your Athena table using this instruction https://docs.aws.amazon.com/athena/latest/ug/wa...