def main():
with open('S3.csv', 'w') as csvfile:
writer = csv.writer(csvfile)
writer.writerow([
'Account Name',
'Region',
'Bucket Name',
'Policy'
])
with open('role.json') as ec2_file:
ec2_data = json.load(ec2_file)
region_list = ['eu-west-1']
for region in region_list:
for index in range(len(ec2_data['Items'])):
Account_Number = ec2_data['Items'][index]['Aws_Account_Number']
Account_Name = ec2_data['Items'][index]['Acc_Name']
ARN = ec2_data['Items'][index]['ARN']
b = get_assume_arn_to_keys(Account_Number,Account_Name,ARN)
ds_client = boto3.client('s3',region_name=region,aws_access_key_id=``,aws_secret_access_key=``,aws_session_token=``)
s3 = boto3.resource('s3')
for bucket in s3.buckets.all():
writer.writerow([
Account_Name,
region,
bucket.name,
ds_client.get_bucket_lifecycle(Bucket=bucket.name)
main()
我想在.csv中列出s3存储桶及其生命周期策略。我可以列出所有存储桶。
但是,列出生命周期策略会给我带来问题。我无法列出所有存储桶。可能,这只是给我第一个桶的政策。
如果我直接输入存储桶名称,我就能获得生命周期策略。 所有存储桶中均列出了单个存储桶“ k”策略。
ds_client.get_bucket_lifecycle(Bucket='k')
但是,如果我想全力以赴,我尝试了
ds_client.get_bucket_lifecycle(Bucket=bucket.name)
编辑::: 尝试列出日志记录,区域和版本控制的新方法。
import boto3
s3_client = boto3.client('s3')
bucket_list = ds_client.list_buckets()
for bucket in bucket_list['Buckets']:
try:
lifecycle = ds_client.get_bucket_lifecycle(Bucket=bucket['Name'])
rules = lifecycle['Rules']
except:
rules = 'No Policy'
versioning = ds_client.get_bucket_versioning(Bucket=bucket['Name'])
logging = ds_client.get_bucket_logging(Bucket=bucket['Name'])
print(bucket['Name'], rules, versioning, logging)
但是无法理解。 友善的建议。 谢谢
答案 0 :(得分:1)
尝试针对没有没有策略的存储桶检索生命周期策略会导致异常。
因此,您将需要像这样使用try/except
:
import boto3
s3 = boto3.resource('s3')
for bucket in s3.buckets.all():
try:
rules = bucket.Lifecycle().rules
except:
rules = 'No Policy'
print(bucket.name, rules)
或客户端版本:
import boto3
s3_client = boto3.client('s3')
bucket_list = s3_client.list_buckets()
for bucket in bucket_list['Buckets']:
try:
lifecycle = s3_client.get_bucket_lifecycle(Bucket=bucket['Name'])
rules = lifecycle['Rules']
except:
rules = 'No Policy'
print(bucket['Name'], rules)