如何使用 Python 和 Boto3 从 S3 Bucket 读取 Txt 文件

How to read Txt file from S3 Bucket using Python And Boto3

如何使用 Python 和 Boto3 从 S3 存储桶读取 Txt 文件 我正在使用以下运行良好的脚本我能够看到 S3 存储桶中的实例名称

import boto3
import codecs

access_key = "XXXXXXXXXXXX"
secret_key = "XXXXXXXXXXXXXXXxxxxx"
ec2 = boto3.client('ec2', aws_access_key_id=access_key, aws_secret_access_key=secret_key, region_name='us-east-1')

s3 = boto3.resource('s3', aws_access_key_id=access_key, aws_secret_access_key=secret_key, region_name='us-east-1')

bucket = 'stoppedinstanceidslist'
key = 'StoppedInstanceidsList.txt'
obj = s3.Object(bucket, key)
InstancetobeStart = (obj.get()['Body'].read().decode('utf-8'))
ids=InstancetobeStart
print(type(ids))   # <class 'str'>
print(ids)  #  ['i-041fb789f1554b7d5', 'i-0d0c876682eef71ae']

response =ec2.start_instances(InstanceIds=ids)

print("Your Instances are Started now which are stopped last day")

使用响应后出现以下错误

    raise ParamValidationError(report=report.generate_report())
botocore.exceptions.ParamValidationError: Parameter validation failed:
Invalid type for parameter InstanceIds, value: ['i-041fb789f1554b7d5', 'i-0d0c876682eef71ae'], type: <class 'str'>, valid types: <class 'list'>, <class 'tuple'>
<class 'str'>
['i-041fb789f1554b7d5', 'i-0d0c876682eef71ae']

如果我的程序在从 s3 存储桶读取后停止实例怎么办

您的 ids 是文字字符串 ['i-041fb789f1554b7d5', 'i-0d0c876682eef71ae'],不是列表。要解析它并转换为列表,请使用 ast 模块:

import ast
# ...
InstancetobeStart = (obj.get()['Body'].read().decode('utf-8'))
ids = ast.literal_eval(InstancetobeStart)