尝试从AWS Lambda连接到Boto3客户端并接收超时

2024-05-16 14:59:37 发布

您现在位置:Python中文网/ 问答频道 /正文

当我在Amazon虚拟私有云(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'])

Tags: the函数nameclientamazongetsecretvalue
1条回答
网友
1楼 · 发布于 2024-05-16 14:59:37

当Lambda驻留在AWS网络中时,它可以使用internet连接到这些服务,但是一旦它加入您的VPC,出站internet流量也会通过您的VPC路由。由于可能没有出站互联网连接,Lambda无法连接互联网

If your function needs internet access, use network address translation (NAT). Connecting a function to a public subnet doesn't give it internet access or a public IP address.

为了使您的Lambda能够在驻留在VPC内时与其他AWS服务通信,必须具备以下条件之一

第一个选项是创建NAT gatewayNAT instance,然后将其添加到Lambda所在的route table。为了清楚起见,此子网应该是专用子网,因为通过对0.0.0.0/0记录使用NAT,它将停止到具有共享同一子网的公共IP地址的实例的入站流量

第二种选择是使用VPC endpoints进行服务,通过这样做,以前通过公共internet的任何流量都将使用直接到AWS服务本身的专用连接。请注意,并不是所有AWS服务都包含在这项服务中

相关问题 更多 >