I have difficulty to get a Lambda function consistently to talk to a VPC peered to the VPC that the lambda function is connected. I believe my configuration is identical to https://aws.amazon.com/premiumsupport/knowledge-center/lambda-dedicated-vpc/ , so I think this is a supported situation, and I will describe.
- I have a lambda function connected to VPC A (us-east-1).
- VPC A and VPC B (us-west-2) are peered.
- A RDS database resides in VPC B and I need the lambda function to talk to it.
The current situation is sometimes they talk (port is open), and sometimes they cannot (port is not open). I do not know what causes one situation or the other, but I have a reproducer and can freely reproduce either scenario by redeploy the lambda, or simply wait after the deployment.
The reproducer lambda function:
import socket
def lambda_handler(event, context):
host = "aurora-xxx.cluster-xxx.us-west-2.rds.amazonaws.com"
ip=socket.gethostbyname(host)
port = 5432
a_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
location = (ip, port)
a_socket.settimeout(10)
result_of_check = a_socket.connect_ex(location)
a_socket.settimeout(None)
if result_of_check == 0:
print(f'Host {host}({ip}) port {port} is open.')
else:
print(f'Host {host}({ip}) port {port} is NOT open.')
And the AWS CLI that deploys the lambda is:
aws --region us-east-1 lambda delete-function --function-name test-2
aws --region us-east-1 lambda create-function --function-name test-2 --zip-file fileb://../lambda/lambda_function.zip --handler lambda_function.lambda_handler --runtime "python3.7" --role <role_arn> --vpc-config SubnetIds=subnet1,subnet2,SecurityGroupIds=sg-xxx --timeout 120
PS: The VPC A and VPC B are peered correctly and port is always open, because I can use psql on an instance in VPC A to connect to the RDS in VPC B. I need the lambda function talks to the RDS outside of its own VPC, because the RDS is part of global database which can be failed over to either VPC.