Home > Blockchain >  Append String in a file Using Python Boto 3
Append String in a file Using Python Boto 3

Time:03-03

I am writing one Lambda function using Python. And I need to collect a list of AMIs which is having a specified tag key-value pair and write it to an S3 Bucket as a JSON file. My code is in below,

import boto3

import json

client = boto3.client('ec2') 


def lambda_handler(event, context):
    
    response = client.describe_images(Owners=['self'])
    versions = response['Images']
    for x in range(len(versions)):
        if {'Key': 'product', 'Value': 'code'} in  response['Images'][x]['Tags']:
            ImageId=versions[x]['ImageId']
            print(ImageId)
            s3 = boto3.resource('s3')
            obj = s3.Object('my-ami-bucketforelk','hello.json')
            obj.put(Body=json.dumps(ImageId))

My Lambda is working as expected except for one thing. My output is overwriting. So I am only able to write one AMI ID at a time.

Can somebody help me to resolve this issue?

CodePudding user response:

You're writing the object to S3 for each and every image ID. Instead, accumulate the image IDs in a list, and then upload that to S3 at the end. For example:

import json
import boto3

ec2 = boto3.client('ec2')
s3 = boto3.resource('s3')

def lambda_handler(event, context):
    response = ec2.describe_images(Owners=['self'])
    versions = response['Images']
    images = []

    for x in range(len(versions)):
        if {'Key': 'product', 'Value': 'code'} in response['Images'][x]['Tags']:
            ImageId=versions[x]['ImageId']
            images.append(ImageId)

    obj = s3.Object('my-ami-bucketforelk', 'hello.json')
    obj.put(Body=json.dumps(images))
  • Related