python - 使用 Boto3 Lambda 函数进行 S3 存储桶生命周期配置并收到 MalformedXML 格式错误

标签 python amazon-web-services amazon-s3 aws-lambda boto3

我创建了 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/

相关文章:

javascript - web.input() 不接收表单数据

linux - 使用浏览器和 IP 而不是 DNS 访问服务器

apache-spark - Spark : How to overwrite a file on S3 folder and not complete folder

ios - 使用 xCode 和 Amazon S3 创建正确的 NSString 以进行图像上传

python - 类型错误 : '<' not supported between instances of 'tuple' and 'str'

python - 使用 BS,当某些迭代中缺少行时循环遍历标签 python3

python - 将不同扩展名的文件名写入不同的文本文件

java - AWS S3 Presign Url 总是同时过期?

ruby-on-rails - Amazon S3 缓存音频文件

amazon-web-services - 通过 AWS CLI 将文件上传到 S3 时出现 "Broken pipe"