【问题标题】:Add multiple S3 lifecycle rules to S3 bucket with boto3使用 boto3 将多个 S3 生命周期规则添加到 S3 存储桶
【发布时间】:2022-01-17 08:31:49
【问题描述】:

我想使用 lambda 和 boto3 向 S3 存储桶添加多个生命周期规则。但是,对于 boto3,它似乎只允许您添加 1 个生命周期规则,这也会覆盖已经存在的规则。

例如,执行以下操作只会覆盖我现有的所有规则以及新编写的规则,并且只保留列表中的最后一条:

bucket_name = "test-bucket"
folder_paths = ["test_folder","test_folder1", "test_folder2"]
expiration = 1

for folder_path in folder_paths:
    client = boto3.client('s3')
    response = client.put_bucket_lifecycle_configuration(
        Bucket=bucket_name,
        LifecycleConfiguration={
            'Rules': [
                {
                    'Expiration': {
                        'Days': expiration
                    },
                    'ID': folder_path,
                    'Filter': {
                        'Prefix': folder_path
                    },
                    'Status': 'Enabled'
                }
            ]
        }
    )

当然,使用 AWS 控制台可以在一个存储桶上添加多个单独的 S3 生命周期配置。

类似于put_bucket_lifecycle_configuration,我也尝试过put_bucket_lifecycle,结果相同。

有没有办法使用 boto3 在一个存储桶上添加多个 S3 生命周期配置?我错过了什么明显的东西吗?

任何帮助表示赞赏并提前感谢!

【问题讨论】:

    标签: amazon-web-services amazon-s3 aws-lambda boto3 s3-lifecycle-policy


    【解决方案1】:

    当然,使用 AWS 控制台可以在一个存储桶上添加多个单独的 S3 生命周期配置。

    每个存储桶都有 1 个生命周期配置,最多可以有 1000 条规则。 您的控制台可能会显示类似的内容:

    这些不是不同的生命周期配置,它们是同一生命周期配置的不同规则部分。

    put_bucket_lifecycle_configuration 的输入中,我们可以看到我们可以传递一个规则列表,其中可以包含一个或多个(最多 1000 个)规则。

    for folder_path in folder_paths:
        client = boto3.client('s3')
        response = client.put_bucket_lifecycle_configuration(
            Bucket=bucket_name,
            LifecycleConfiguration={
                'Rules': [
                    {
                        'Expiration': {
                            'Days': expiration
                        },
                        'ID': id_rule_1,
                        'Filter': {
                            'Prefix': folder_path
                        },
                        'Status': 'Enabled'
                    },
                    {
                        'Expiration': {
                            'Days': expiration2
                        },
                        'ID': id_rule_2,
                        'Filter': {
                            'Prefix': folder_path2
                        },
                        'Status': 'Enabled'
                    },
                 ...
                ]
            }
        )
    

    正如文档所说,put_bucket_lifecycle_configuration为存储桶创建新的生命周期配置或替换现有的生命周期配置。”如果要更新生命周期配置,则必须使用 @987654323 @ 检索现有规则,修改它们,然后使用put_bucket_lifecycle_configuration 覆盖现有配置。

    【讨论】:

      猜你喜欢
      • 2019-08-17
      • 2022-01-02
      • 2020-12-10
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 2021-02-07
      • 2021-12-07
      • 1970-01-01
      相关资源
      最近更新 更多