我正在使用 Python 撰寫一個 Lambda 函式。我需要收集具有指定標簽鍵值對的 AMI 串列,并將其作為 JSON 檔案寫入 S3 存盤桶。我的代碼在下面,
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))
我的 Lambda 按預期作業,除了一件事。我的輸出被覆寫。所以我一次只能寫一個 AMI ID。
有人可以幫我解決這個問題嗎?
uj5u.com熱心網友回復:
您正在將每個影像 ID 的物件寫入 S3。相反,將影像 ID 累積在一個串列中,然后在最后將其上傳到 S3。例如:
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))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/436178.html
標籤:Python python-3.x 亚马逊网络服务 aws-lambda 博托3
