我创建了 lambda 函数。在函数中,如果存储桶名称包含“log”单词,我扫描了所有 s3 存储桶。获取这些存储桶并应用生命周期。如果保留时间超过 30 天,请删除存储桶下包含“log”字样的所有类型的文件。但是当我触发代码时,我收到此格式错误。我无法修复它。我的代码或格式是否错误?
这是我的Python代码:
import logging
import boto3
import datetime, os, json, boto3
from botocore.exceptions import ClientError
def lambda_handler(event, context):
s3 = boto3.client('s3')
response = s3.list_buckets()
# Output the bucket names
print('Existing buckets:')
for bucket in response['Buckets']:
#print(f' {bucket["Name"]}')
if 'log' in bucket['Name']:
BUCKET = bucket["Name"]
print (BUCKET)
try:
policy_status = s3.put_bucket_lifecycle_configuration(
Bucket = BUCKET ,
LifecycleConfiguration={'Rules': [{'Expiration':{'Days': 30,'ExpiredObjectDeleteMarker': True},'Status': 'Enabled',} ]})
except ClientError as e:
print("Unable to apply bucket policy. \nReason:{0}".format(e))
错误
Existing buckets:
sample-log-case
sample-bucket-log-v1
template-log-v3-mv
Unable to apply bucket policy.
Reason:An error occurred (MalformedXML) when calling the PutBucketLifecycleConfiguration operation: The XML you provided was not well-formed or did not validate against our published schema
我从 boto3 网站获取了以下示例,我只是更改了参数并没有触及格式,但我也遇到了格式问题:
import boto3
client = boto3.client('s3')
response = client.put_bucket_lifecycle_configuration(
Bucket='bucket-sample',
LifecycleConfiguration={
'Rules': [
{
'Expiration': {
'Days': 3650,
},
'Status': 'Enabled'
},
],
},
)
print(response)
最佳答案
根据the documentation ,如果 LifecycleRule
不包含 'Prefix' 元素(不再使用 'Prefix' 元素),则需要 'Filter' 规则。反过来,“过滤器”需要“前缀”、“标签”或“和”之一。
将以下内容添加到 LifecycleConfiguration
中的“规则”中将解决该问题:
'Filter': {'Prefix': ''}
关于python - 使用 Boto3 Lambda 函数进行 S3 存储桶生命周期配置并收到 MalformedXML 格式错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66357302/