捕获 AWS lambda 函数的输出并通过 SNS 通过电子邮件发送

发布于 2025-01-11 04:10:24 字数 1332 浏览 0 评论 0原文

Lambda 函数代码:

import json
import datetime
import redshift_module.pygresql_redshift_common as db_handler
from decouple import config
import pg

host = config('host')
port = config('port')
db_name = config('db_name')
db_user = config('db_user')
db_password = config('db_password')


def get_connection(host, port, dbname, user, password):
    rs_conn_string = "host=%s port=%s dbname=%s user=%s password=%s" % (
        host, port, dbname, user, password)
    rs_conn = pg.connect(dbname=rs_conn_string)
    rs_conn.query("set statement_timeout = 1200000")
    return rs_conn


def query(con, query):
    res = con.query(query)
    return res


rs_conn = db_handler.get_connection(host, port, db_name, db_user, db_password)
query_string = "call XYZ_warehouse.ABC_revenue_last_7_days();"

res = query(rs_conn, query_string)
print(res.getresults())


def lambda_handler(event, context):
    return {'statusCode': 200, 'body': json.dumps('Hello from Lambda!')}

代码在 redshift 数据库上运行查询函数。 lambda 的输出包含如下字符串:

DEUS revenue is completely matching and revenue is : 5139 and Revenue without shipping is: 4987

我需要做的是捕获执行结果中的此类行,也许将它们存储在变量中或日志文件中的某处,以便我可以通过电子邮件发送它们。我尝试在查询对象上运行 .getresults() 但它返回一个空字符串。也许是因为它没有返回记录或表格?

有没有办法捕获 lambda 函数的完整输出?或者将其发送到某处的文件中?

Lambda function code:

import json
import datetime
import redshift_module.pygresql_redshift_common as db_handler
from decouple import config
import pg

host = config('host')
port = config('port')
db_name = config('db_name')
db_user = config('db_user')
db_password = config('db_password')


def get_connection(host, port, dbname, user, password):
    rs_conn_string = "host=%s port=%s dbname=%s user=%s password=%s" % (
        host, port, dbname, user, password)
    rs_conn = pg.connect(dbname=rs_conn_string)
    rs_conn.query("set statement_timeout = 1200000")
    return rs_conn


def query(con, query):
    res = con.query(query)
    return res


rs_conn = db_handler.get_connection(host, port, db_name, db_user, db_password)
query_string = "call XYZ_warehouse.ABC_revenue_last_7_days();"

res = query(rs_conn, query_string)
print(res.getresults())


def lambda_handler(event, context):
    return {'statusCode': 200, 'body': json.dumps('Hello from Lambda!')}

So the code runs a query function on a redshift database.
The output of the lambda contains strings like following:

DEUS revenue is completely matching and revenue is : 5139 and Revenue without shipping is: 4987

What i need to do is capture lines like these in the execution results, maybe store them in a variable or in a log file somewhere so i can then email them. Ive tried running .getresults() on the query object but it returns an empty string. Maybe because its not returning a record or a table?

Is there a way i can capture the complete output of a lambda function? or send it to a file somewhere?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

谁把谁当真 2025-01-18 04:10:24

创建字典并保存您想要通过电子邮件发送的所有输出。

现在将其转换为 json 并通过 SNS 或 SES 发送

Create dictionary and save all output you want to send via email.

Now convert it to json and send via SNS or SES

很糊涂小朋友 2025-01-18 04:10:24

您的问题有点不清楚,您是否还需要检索查询结果方面的帮助?

如果是这样,我建议您从此处阅读

有没有办法捕获 lambda 函数的完整输出?或者将其发送到某个文件?

一种选择是将 lambda func 的输出发送到 s3 存储桶,例如

import boto3

s3 = boto3.resource(
    's3',
    region_name='us-east-1',
    aws_access_key_id=KEY_ID,
    aws_secret_access_key=ACCESS_KEY
)
content="String content to write to a new S3 file"
s3.Object('my-bucket-name', 'newfile.txt').put(Body=content)

您可以设置一个 s3 触发器,然后 将新对象添加到存储桶后立即触发第二个 lambda

然后,您的第二个 lambda 可以转换为 JSON 并通过 SNS/SES 作为 Vaquar Khan 的答案发送。

Your question is a bit unclear, do you also want help with retrieving your query results?

If so I suggest you read from here

Is there a way i can capture the complete output of a lambda function? or send it to a file somewhere?

One option is to send the output of your lambda func to an s3 bucket e.g.

import boto3

s3 = boto3.resource(
    's3',
    region_name='us-east-1',
    aws_access_key_id=KEY_ID,
    aws_secret_access_key=ACCESS_KEY
)
content="String content to write to a new S3 file"
s3.Object('my-bucket-name', 'newfile.txt').put(Body=content)

you can set up an s3 trigger that will then trigger a second lambda as soon as a new object is added to the bucket.

Your second lambda can then transform to JSON and send via SNS/SES as Vaquar Khan's answer.

调妓 2025-01-18 04:10:24

如果我理解正确的话“你想将 lambda 的输出存储在单独的位置/文件中”以将其用作电子邮件。

如果它是纯 lambda 输出,您可以简单地使用 lambda 目标

目标允许您根据失败或成功来分离结果。如果成功,您可以将其发送到目标(SNS、SQS、EventBridge 或不同的 Lambda),如果失败,您可以将其发送到失败目的地

目标文档

If i understood correctly " you want to store output of lambda in separate place/file" to use it as email.

If it is a pure lambda output you can simple use lambda destinations.

Destinations allows you to segregate results based on failure or success. if it is success you can send it to a target ( SNS, SQS, EventBridge or different Lambda), if it is failure you can send it to failure destination

Destinations docs

初心 2025-01-18 04:10:24

创建

作为初学者,我想到的解决方案是:

  • 另一个由 CloudwatchLogs 触发的 lambda 函数。
  • 选择输出查询结果的函数的日志组。它的日志将包含您需要的行。
  • 要从日志中获取这些行,您需要以下代码:
    • decoded_data = json.loads(gzip.decompress(b64decode(event['awslogs']['data'])))
      
    • 从查询 lambda 函数创建的最新日志将存储在 decoded_data
    • 然后从词典中提取所需的行并通过 SNS 通过电子邮件发送。

Solved

The solution I figured out as a beginner is:

  • Create another lambda function that is triggered with CloudwatchLogs.
  • Choose the log group of the function that is outputting the query result. Its logs will have the lines you need.
  • To get those lines from the logs you need this code:
    • decoded_data = json.loads(gzip.decompress(b64decode(event['awslogs']['data'])))
      
    • The latest log created from your query lambda function will be stored in decoded_data
    • Then extract the line you want from the dictionary and email it via SNS.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文