当我在Amazon Virtual Private Cloud(Amazon VPC)之外运行它时,我的AWS Lambda函数代码可以正常工作。但是,当我将功能配置为连接到VPC时,会出现功能超时错误。我该如何解决?
def get_db_connection_config():
# Create a Secrets Manager client.
session = boto3.session.Session()
client = session.client(
service_name='secretsmanager',
region_name=region_name
)
# In this sample we only handle the specific exceptions for the 'GetSecretValue' API.
# See https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
# We rethrow the exception by default.
try:
logger.info("Retrieving MySQL database configuration...")
get_secret_value_response = client.get_secret_value(
SecretId=secret_name
)
except ClientError as error:
logger.error(error)
sys.exit()
else:
# Decrypts secret using the associated KMS CMK.
# Depending on whether the secret is a string or binary, one of these fields will be populated.
if 'SecretString' in get_secret_value_response:
secret = get_secret_value_response['SecretString']
return json.loads(secret)
else:
return base64.b64decode(get_secret_value_response['SecretBinary'])
答案 0 :(得分:1)
当Lambda驻留在AWS网络中时,它可以使用Internet连接到这些服务,但是,一旦加入您的VPC,出站Internet流量也将通过您的VPC路由。由于可能没有出站互联网连接,因此Lambda无法访问互联网。
如果您的功能需要Internet访问,请使用网络地址转换(NAT)。将功能连接到公共子网不会为其提供Internet访问或公共IP地址。
为了使Lambda能够在其位于VPC内时与其他AWS服务进行通信,必须具备以下条件之一。
第一种选择是创建一个NAT gateway或NAT instance,然后将其添加到Lambda所驻留的route table中。要清楚,此子网应该是专用子网只有通过将NAT用于0.0.0.0/0
记录,才能阻止到具有共享同一子网的公共IP地址的实例的入站流量。
第二个选择是您将VPC endpoints用于服务,通过这样做,以前已经遍历公共互联网的任何流量都将直接使用专用连接到AWS服务本身。请注意,目前还没有涵盖所有的AWS服务。