I have a MySQL server on a lightsail instance. The goal is to access the MySQL server from a lambda function.
What I did is as follows.
- Turn on VPC peering of lightsail
- Create a MySQL user with '%' host
- Add the following policies to the lambda function (AmazonEC2FullAccess, AWSLambdaBasicExecutionRole, AWSLambdaVPCAccessExecutionRole)
- Open port 3306 on the firewall of the lightsail
- Comment out the bind-address in /opt/bitnami/mysql/my.cnf and reboot MySQL
The lambda code and app.py for CDK are below. The result is the following error. If I try to connect to the same MySQL server with the same code from another EC2 instance in the same VPC/subnet, I can connect successfully.
What do I miss?
[ERROR] OperationalError: (2003, "Can't connect to MySQL server on 'host' (timed out)")
Traceback (most recent call last):
File "/var/task/hello.py", line 13, in main
con=MySQLdb.connect(host=host,db=db,user=user,passwd=pw,charset="utf8");
File "/opt/python/pymysql/connections.py", line 353, in __init__
self.connect()
File "/opt/python/pymysql/connections.py", line 664, in connect
raise exc
Lambda function (hello.py)
import pymysql as MySQLdb;
def main(event, context):
print("hello");
con=MySQLdb.connect(host=host,db=db,user=user,passwd=pw,charset="utf8");
print("done");
app.py
from aws_cdk import (
aws_lambda as lam,
aws_iam as iam,
aws_ec2 as ec2,
core,
)
import os;
class MyStack(core.Stack):
def __init__(self, app: core.App, id: str) -> None:
super().__init__(app, id)
vpc = ec2.Vpc.from_vpc_attributes(
self,"VPC",
vpc_id=vpcid,
availability_zones=[zone],
isolated_subnet_ids=[subnet],
);
sg = ec2.SecurityGroup.from_security_group_id(
self,"SG",
security_group_id=sgid,
mutable=False
);
layer = lam.LayerVersion(
self, "MyLayer",
code=lam.AssetCode.from_asset('./lib'),
);
lamrole = iam.Role.from_role_arn(
self, "LambdaRole",
rolearn,
);
helloFn = lam.Function(
self, "hello",
function_name='hello',
code=lam.AssetCode.from_asset('./code'),
handler="hello.main",
timeout=core.Duration.seconds(900),
role=lamrole,
vpc=vpc, # for mysql
security_groups=[sg],
layers=[layer],
runtime=lam.Runtime.PYTHON_3_7,
)
app = core.App()
MyStack(app, "hello")
app.synth()