Lambda函数写入csv并上传到S3

2024-05-19 12:24:40 发布

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

我有一个Python脚本,它获取未使用的安全组的详细信息。 我想把它写入一个CSV文件并上传到s3bucket。在

当我在本地机器上测试它时,它会在本地机器中写入CSV。但是当我把它作为lambda函数执行时,它需要一个地方来保存CSV。所以我使用s3。在

import boto3
import csv

ses = boto3.client('ses')

def lambda_handler(event, context):
    with open('https://unused******- 
    1.amazonaws.com/Unused.csv', 'w') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow([
            'Account Name',
            'Region',
            'Id'
        ])
        ec2 = boto3.resource('ec2')
        sgs = list(ec2.security_groups.all())
        insts = list(ec2.instances.all())

        all_sgs = set([sg.group_id for sg in sgs])
        all_inst_sgs = set([sg['GroupId'] for inst in insts for sg in
        inst.security_groups])

        unused_sgs = all_sgs - all_inst_sgs


        for elem in unused_sgs:
            writer.writerow([
                Account_Name,
                region,
                elem
                ])

我想把“elem”的结果写入csv文件并上传到S3 Bucket。 恳请指教。在


Tags: 文件csvin机器forunusedallsg
3条回答

如果CSV文件很小,请将其写入/tmp文件夹,然后将该文件上载到S3。如果它很大(比如,大于~200MB),那么您可能应该将其流式传输到S3。在

阅读有关S3 client methods的boto3文档。在

通过使用StringIO(),您不需要将csv保存到本地,只需将IO上传到S3。试试我的代码,如果出了什么问题让我知道,因为我不能测试代码,但它对其他情况有效。在

import boto3
import csv
import io

s3 = boto3.client('s3')
ses = boto3.client('ses')

def lambda_handler(event, context):
    csvio = io.StringIO()
    writer = csv.writer(csvio)
    writer.writerow([
        'Account Name',
        'Region',
        'Id'
    ])

    ec2 = boto3.resource('ec2')
    sgs = list(ec2.security_groups.all())
    insts = list(ec2.instances.all())

    all_sgs = set([sg.group_id for sg in sgs])
    all_inst_sgs = set([sg['GroupId'] for inst in insts for sg in
    inst.security_groups])

    unused_sgs = all_sgs - all_inst_sgs

    for elem in unused_sgs:
        writer.writerow([
            Account_Name,
            region,
            elem
            ])

    s3.put_object(Body=csvio.getvalue(), ContentType='application/vnd.ms-excel', Bucket='bucket', Key='name_of.csv') 
    csvio.close()

如果csv文件很小,请遵循jarmod的建议,否则可以使用lambda来启动一个临时ec2实例(您可以选择xlarge以获得更好的性能),其中包含用户数据。user_data将在一个强大且健康的ec2上执行所有csv进程,不过记住在进程完成后终止实例(termination命令也可以包含在user_数据中)。在

相关问题 更多 >