Cloud Custodian OCI 实战:用 tag-public-buckets 策略标记所有公开对象存储桶

原创2026-10-09 13:59:001,928 阅读
文章标签:云原生运维安全

Cloud Custodian OCI 实战:用 tag-public-buckets 策略标记所有公开对象存储桶

本篇围绕 Cloud Custodian OCI 提供者中 bucket_tagpublic_storage.rst 示例文档展开:如何写出一条 YAML 策略,筛选出 Oracle Cloud Infrastructure(OCI)中所有公开可读取的对象存储桶(Bucket),并自动打上 public_access: true 自由格式标签。读完本文,你将理解该策略中 attributes 过滤器与 update 动作的完整调用链、标签合并的底层语义,以及如何与“收回公开访问权限”策略串联成两步治理流程,并能通过仓库中的 VCR 测试用例验证策略行为。

1. 示例策略原文与逐字段解读

关联文档给出的完整策略如下(文档中的 YAML 缩进已规范化,字段未做改动):

policies:
- name: tag-public-buckets
  description: Tag all the public buckets in the tenancy
  resource: oci.bucket
  filters:
  - type: attributes
    key: public_access_type
    value: 'ObjectRead'
    op: eq
  actions:
  - type: update
    freeform_tags:
      public_access: 'true'

各字段含义逐条说明:

字段 取值 说明
resource oci.bucket 目标资源类型,由 OCI 提供者的资源注册表映射到 object_storage.py 中的 Bucket 资源管理器
filters[0].type attributes Bucket 专属过滤器,会先拉取每个桶的完整属性再做条件判断(见第 3 节)
filters[0].key public_access_type OCI 桶的公开访问属性字段,ObjectRead 表示允许匿名读取对象
filters[0].value / op 'ObjectRead' / eq 等值匹配:只保留 public_access_type == ObjectRead 的桶
actions[0].type update 桶的更新动作,支持 freeform_tags、defined_tags、public_access_type 三类参数
freeform_tags public_access: 'true' 命中的桶将被写入自由格式标签,标记为“公开桶”,供后续治理策略消费

策略的意图很直接:公开桶是一种安全治理关注点,但直接批量改访问权限风险较高。先“打标”再“处置”,把命中集合显性化,是 OCI 示例文档推荐的治理路径——bucket_access_storage.rst 紧接着就给出了第二步:按该标签把桶改回私有。

2. 策略如何被查询与执行:资源源与命名空间

oci.bucket 的查询并非简单地调一次 list API。从源码看,query.py 中 QueryResourceManager.source_type(L224-L229)依据环境变量做二选一:

  • 设置了 OCI_COMPARTMENTS(常量定义见 constants.py L13 的 COMPARTMENT_IDS)时,走 describe-native 源:按逗号分隔的多个 compartment OCID 逐个调用 ObjectStorageClient.list_buckets,并支持结果缓存;
  • 未设置时,走 describe-search 源:先通过 ResourceSearchClient.search_resources 做结构化检索(query bucket resources),再按命中的 compartment 回查完整资源。

桶资源还有一处关键补充:object_storage.py 中 Bucket._get_extra_params()(L46-L49)会调用 get_client().get_namespace().data 自动填入 namespace_name。也就是说,策略里不需要手写命名空间,查询层会自动解析当前租户的存储命名空间后注入 list 调用。

查询范围的控制方式与同目录的 bucket_query_storage.rst 文档一致:默认在 tenancy 级别查询,export OCI_COMPARTMENTS=<compartment OCID>,... 可缩小到指定 compartment。

3. attributes 过滤器:为什么需要它

list_buckets 返回的是桶的概要信息,而判断公开访问状态需要桶的完整属性。attributes 过滤器就是为此注册的,实现位于 object_storage.py:

@Bucket.filter_registry.register("attributes")
class AttributesValueFilter(ValueFilter):
    schema = type_schema("attributes", rinherit=ValueFilter.schema)

    def process(self, resources, event):
        result = []
        for resource in resources:
            response = self.manager.get_client().get_bucket(
                namespace_name=resource.get("namespace"),
                bucket_name=resource.get("name"),
            )
            bucket = oci.util.to_dict(response.data)
            resource = {**resource, **bucket}
            result.append(resource)
        return super().process(result)

执行流程是:

  1. 对每个候选桶调用 ObjectStorageClient.get_bucket 拉取完整属性字典(包含 public_access_type、namespace、标签等);
  2. 将完整属性合并(merge)进资源对象;
  3. 交还给核心 ValueFilter 执行 key/value/op 判定——本例即 public_access_type == 'ObjectRead'。

ValueFilter 继承自 Custodian 核心 filters/core.py,因此 key 支持点号路径(如 freeform_tags.public_access),op 支持 eq、ne、in 等通用比较符,可按需替换为 op: ne 配合 value: NoPublicAccess 之类的反向条件。

需要留意的是性能特征:该过滤器对每个桶都会额外发起一次 get_bucket 调用,桶数量很大时查询阶段会产生与桶数成正比的 API 请求,这是使用 attributes 类型过滤器的固有代价。

4. update 动作:标签写入与合并语义

update 动作实现在 object_storage.py 的 UpdateBucketAction 中,其 schema 只接受三个可选参数:

schema = type_schema(
    "update",
    **{
        "freeform_tags": {"type": "object"},
        "defined_tags": {"type": "object"},
        "public_access_type": {"type": "string"},
    },
)

执行时把资源现有的 namespace 和 name 作为调用参数,将策略参数封装为 UpdateBucketDetails 模型后调用 client.update_bucket(...)。

标签不会简单覆盖,而是先合并。基类 actions/base.py 的 update_params 负责这一语义:

  • freeform_tags:取资源现有自由标签,仅当策略给定的键值与现有值不同时才视为“变更”,最终以 {现有标签, 新标签} 合并结果下发。也就是说,本例策略只会新增 public_access,不会抹掉桶上已有的 Environment、Project 等标签;
  • defined_tags:按命名空间做同样的合并处理。

这一合并逻辑保证策略可重复执行(幂等):对已经带 public_access: 'true' 的桶再次运行,不会产生额外的标签变更,也不会影响其他标签。

基类的异常处理同样值得了解:OCIBaseAction.process(base.py)对每个资源逐个执行 perform_action,单个资源失败默认会向上抛出(fail_on_error 默认为 True),动作 schema 中可通过 fail_on_error: false 降级为记录到 failed_resources 并继续处理其余资源。

5. 两步治理流程:打标之后收回公开访问权限

tag-public-buckets 打出的标签正是姊妹策略的过滤条件。bucket_access_storage.rst 文档中的策略:

policies:
- name: set-private-bucket
  description: Filter the buckets and set the visibility to private
  resource: oci.bucket
  filters:
  - type: value
    key: "freeform_tags.public_access"
    value: 'true'
    op: eq
  actions:
  - type: update
    public_access_type: 'NoPublicAccess'

注意这里用的是普通的 value 过滤器而非 attributes——freeform_tags 在 list 阶段就已随资源返回(enum_spec 中 fields: ["tags"] 保证标签字段被拉取),无需再逐个 get_bucket。两条策略串起来形成完整闭环:

  1. 第一步标记所有 public_access_type: ObjectRead 的桶;
  2. 第二步对带标签的桶执行 update,把 public_access_type 置为 NoPublicAccess,公开访问权限即被收回。

仓库测试 test_object_storage.py 的 test_change_public_bucket_to_private 也验证了 update + public_access_type: NoPublicAccess 这一动作路径可用。

6. 测试验证:策略行为有 VCR 用例背书

示例文档并非“纸面策略”。test_object_storage.py 中的 test_tag_public_bucket 与文档策略逐字段等价:

policy = test.load_policy(
    {
        "name": "tag-public-buckets",
        "resource": "oci.bucket",
        "query": [{"namespace_name": namespace_name}],
        "filters": [
            {
                "type": "attributes",
                "key": "public_access_type",
                "value": "ObjectRead",
                "op": "eq",
            },
        ],
        "actions": [{"type": "update", "freeform_tags": {"public_access": "true"}}],
    },
    session_factory=session_factory,
)
policy.run()
resource = self._fetch_bucket_validation_data(
    policy.resource_manager, namespace_name, bucket_name
)
test.assertEqual(resource["name"], bucket_name)
test.assertEqual(resource["freeform_tags"]["public_access"], "true")

该测试基于 pytest_terraform 声明式资源(tests/terraform/object_storage/bucket.tf)与 VCR 回放数据(cassettes/TestObjectStorage.test_tag_public_bucket.yml):策略执行后通过 get_bucket 二次拉取,断言 freeform_tags["public_access"] == "true" 确实落到桶上。也就是说,“筛选公开桶 → 打标签”这条链路在仓库测试中是经过真实 API 交互序列验证的。

7. 运行前提与执行方式

运行该策略前需要完成 gettingstarted.rst 描述的准备工作:

  1. 安装:基础包 pip install c7n,再安装 OCI 提供者 pip install c7n-oci;
  2. 认证:配置 OCI 凭证(如通过 oci setup config 生成配置文件,Custodian 运行时会隐式读取),或在 OCI 实例上设置 export OCI_CLI_AUTH=instance_principal 使用实例主体认证;
  3. 可选:export OCI_COMPARTMENTS=<OCID>,... 将查询限定到指定 compartment,否则默认 tenancy 级查询;
  4. 执行:把策略保存为 YAML 文件后 c7n run tag-public-buckets.yml,多区域场景下可用 --regions all(query.py 与 provider.py 会先通过 list_region_subscriptions 过滤掉租户未开通的区域,未订阅区域会被跳过而非报错)。

8. 后续清理:remove-tag 动作

标记完成治理动作后,如需移除治理标签,同一资源注册了 remove-tag 动作(object_storage.py):

policies:
- name: remove-tag
  resource: oci.bucket
  actions:
  - type: remove-tag
    defined_tags: ['cloud_custodian.environment']
    freeform_tags: ['public_access']

其基类 RemoveTagBaseAction 会先比对删除前后的标签计数,只有确实发生变化时才调用 update_bucket 下发,避免无意义的 API 写入;defined tag 需以 namespace.tagName 形式引用。

小结

tag-public-buckets 示例的价值在于它展示了 OCI 提供者策略编写的三个通用要点:用资源专属的 attributes 过滤器获取完整属性做精确判定;用 update 动作执行带合并语义的幂等写入;以及“先打标、后处置”的两步治理编排。配合 OCI_COMPARTMENTS 控制查询范围、fail_on_error 控制失败行为,这套模式可以直接复用到其他 OCI 资源(实例、VCN、身份用户等)的标签治理场景中。

登录后查看全文
cloud-custodian