【问题标题】:aws lambda put-metric-data timeoutaws lambda put-metric-data 超时
【发布时间】:2021-03-13 09:56:42
【问题描述】:

我需要从 RDS 获取一些数据并将其作为 cloudwatch 指标推送。

我在 AWS 中创建了一个与具有 Internet 访问权限的 VPC 关联的 lambda。但是指标的推送超时。

尝试对此进行调试,我做了一个 dns 解析,并且工作正常。

有什么想法吗?

这是代码:

    print('Loading function')

    try:
        conn = pymysql.connect(host="kmydb.something.eu-west-1.rds.amazonaws.com", user="myuser", passwd="mypass", db="mydb", connect_timeout=5)
        print("SUCCESS: Connection to RDS MySQL instance succeeded")
        item_count = 0

        with conn.cursor() as cur:
            print("Executing SQL command")
            cur.execute("select count(*) from something")
            for row in cur:
                item_count = row[0]
            print("DONE: Executing SQL command -> Rows: {}".format(item_count) )
        conn.commit()
        print("DEBUG: Going to push now.")

        hostName    = "something.something.com"
        ipAddress   = socket.gethostbyname(hostName)
        print("IP address of the host name {} is: {}".format(hostName, ipAddress))

        if pushToCloudwatch(item_count):
            print("DEBUG: Pushed sucessfull.")
        else:
            print("ERROR: Pushed NOT sucessfull.")

    except pymysql.MySQLError as e:
        print("ERROR: Unexpected error: Could not connect to MySQL instance.")
        print("error: {}".format(e))
        sys.exit()


def pushToCloudwatch(channels):
    print("ERROR: Creating client.")
    client = boto3.client('cloudwatch',region_name="us-west-1")
    print("ERROR: client created... pushing.")

    response = client.put_metric_data(
        Namespace='INFRA-VOICE',
        MetricData=[
            {
                'MetricName': 'CurrentP',
                'Dimensions': [
                    {
                        'Name': 'INFRA',
                        'Value': 'CurrentP'
                    },
                ],
                'Value': 0,
                'Unit': 'Count'
            }
        ]
    )
    print("ERROR: Response received.")
    print( "Response: {}".format(response) )
    return True

【问题讨论】:

  • 与 lambda 关联的子网可以访问互联网(互联网网关/nat 网关)?您是否检查了安全组以允许使用 aws api 的出站规则?

标签: aws-lambda amazon-cloudwatch


【解决方案1】:

所以重点是,您必须:

  • 如果您必须创建它,请将您的 lambda 放入私有子网(在您现有的 VPC 中)。
  • 在公共子网上创建一个 NatGateway。
  • 然后在私有子网上,您需要将路由添加到指向 0.0.0.0/0 到 NatGateway(在公共 vpc 上)的路由表
  • NatGateway 将获取您的流量并通过其自己的 Internet 网关 (igw) 将其 NAT 到 Internet

类似这样的:

这对我帮助很大:

Amazon AWS NAT Gatway not working, EC2 doesn't register in ECS Cluster

解决了。

【讨论】:

    猜你喜欢
    • 2020-05-02
    • 2019-04-03
    • 2021-06-08
    • 2021-07-26
    • 1970-01-01
    • 2020-01-18
    • 2017-09-20
    • 2019-11-17
    相关资源
    最近更新 更多