使用 Cloud Custodian 将 OCI 对象存储桶批量切换为私有访问

原创2026-10-11 09:59:111,743 阅读
文章标签:云原生运维安全

使用 Cloud Custodian 将 OCI 对象存储桶批量切换为私有访问

本文基于 Cloud Custodian 仓库的 OCI 示例文档,讲解如何编写一条 oci.bucket 治理策略:先通过 freeform_tags 标签筛选出标记为"允许公共访问"的桶,再使用 update 动作将其可见性(public_access_type)改为 NoPublicAccess(私有)。读完本文,你将掌握 OCI 桶策略的完整编写、运行与验证流程,并能结合仓库源码理解该策略的底层 API 调用链。

一、场景与目标:为什么要把桶设为私有

Oracle Cloud Infrastructure(OCI)对象存储桶支持设置不同的公共访问级别。一旦桶被配置为 ObjectRead 等公共访问类型,任何知道对象 URL 的人都可以在未经认证的情况下读取桶内对象,这极易造成数据泄露。

治理团队通常会在 OCI 上以标签(freeform tags)的形式标注资源用途与开放策略,例如给允许公开读取的桶打上 public_access: 'true' 标签。但当合规要求收紧(如数据分级、安全审计整改)时,需要将这些打了"允许公开"标签的桶统一收口为私有访问。Cloud Custodian 的 OCI 提供商(Beta)为这一场景提供了声明式的 YAML 策略方案:

  1. 过滤(filter):根据 freeform_tags.public_access = true 找出所有被标记为公开的桶;
  2. 动作(action):调用 OCI update_bucket API,把桶的 public_access_type 更新为 NoPublicAccess,实现可见性收口。

与逐个人工修改桶属性相比,这条策略可以在整个租户(tenancy)范围内自动、可重复、可审计地完成批量整改,且天然具备"标签即策略"的可扩展性——后续只需调整标签约定,即可复用同一套治理框架。

二、核心策略拆解:从过滤到整改

原始示例文档给出了如下完整策略(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'

下面逐段拆解每个配置项的含义。

1. resource: oci.bucket:目标资源类型

oci.bucket 是 Cloud Custodian OCI 插件注册的对象存储桶资源。在仓库源码 tools/c7n_oci/c7n_oci/resources/object_storage.py 中可以看到:

@resources.register("bucket")
class Bucket(QueryResourceManager):
    """Oracle Cloud Infrastructure Bucket Resource"""

    class resource_type:
        doc_groups = ["ObjectStorage"]
        service = "oci.object_storage"
        client = "ObjectStorageClient"
        enum_spec = ("list_buckets", "items[]", {"fields": ["tags"]})
        extra_params = {"compartment_id", "namespace_name"}
        resource_type = "OCI.ObjectStorage/Bucket"
        id = name = "name"
        search_resource_type = "bucket"

关键点:

  • 资源枚举走 list_buckets API,并通过 {"fields": ["tags"]} 在列表阶段就拉取标签信息,因此后续可以直接基于 freeform_tags 做值过滤,无需逐个桶回查;
  • id 与 name 均为桶名(name);
  • _get_extra_params 会调用 get_namespace() 自动获取对象存储命名空间(namespace),策略运行时不需要手工指定 namespace。

2. filters:用值过滤选中目标桶

filters:
 - type: value
   key: "freeform_tags.public_access"
   value: 'true'
   op: eq
  • type: value 使用 Cloud Custodian 通用的值过滤器(ValueFilter),对资源字段做条件判断;
  • key 采用点号路径语法,freeform_tags.public_access 表示读取资源字典中 freeform_tags 字典的 public_access 键。由于 list_buckets 已在枚举阶段携带了 tags(见上文 enum_spec),该键值可直接参与过滤;
  • value: 'true' 与 op: eq 表示只保留 public_access 标签值等于字符串 'true' 的桶。

值得注意:该过滤器是精准匹配,只影响显式打了 public_access: 'true' 标签的桶;未打该标签的桶(无论实际是否公开)都不会被选中。这正好体现"标签驱动治理"的设计意图。

3. actions:调用 update 动作收口可见性

actions:
 - type: update
   public_access_type: 'NoPublicAccess'

update 动作在源码中注册于 UpdateBucketAction(object_storage.py),其参数模式为:

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

即 update 动作支持三类参数:

参数 类型 作用
public_access_type string 设置桶的公共访问级别,本例设为 NoPublicAccess(私有)
freeform_tags object 新增/覆盖自由格式标签(键值对)
defined_tags object 新增/覆盖定义标签(按命名空间组织的键值对)

动作执行时调用 OCI Python SDK 的 update_bucket 接口:

def perform_action(self, resource):
    client = self.manager.get_client()
    update_bucket_details_user = self.extract_params(self.data)
    params_model = self.update_params(resource, update_bucket_details_user)
    update_bucket_details = oci.object_storage.models.UpdateBucketDetails(**params_model)
    response = client.update_bucket(
        namespace_name=resource.get("namespace"),
        bucket_name=resource.get("name"),
        update_bucket_details=update_bucket_details,
    )

其中 update_params(定义于 actions/base.py)会对标签类参数做合并而非整体替换处理:freeform_tags 与 defined_tags 会在保留桶上已有标签的基础上,叠加策略中声明的标签变更,避免误删未涉及的其他标签;而 public_access_type 这类标量参数则直接按策略值生效。

三、在真实环境运行这条策略

1. 安装 Cloud Custodian 与 OCI 插件

参考 OCI Getting Started,OCI 提供商是可选扩展包,需先安装基础版 Cloud Custodian,再安装 c7n-oci:

pip install c7n
pip install c7n-oci

2. 配置 OCI 认证

Cloud Custodian 会自动读取 OCI CLI 的配置。先安装 OCI CLI 并执行:

oci setup config

配置完成后,运行策略时即隐式使用该凭据。如果策略运行在 OCI 实例上,还可以启用实例主体认证:

export OCI_CLI_AUTH=instance_principal

3. 保存策略文件并运行

将上文策略保存为 bucket_private.yml,然后在命令行执行:

custodian run --output-dir=. bucket_private.yml

运行成功后,会在 --output-dir 下生成以策略名命名的目录(set-private-bucket/),内含运行日志与结果 JSON 文件,记录被整改的桶清单,便于审计追溯。

4. 控制查询范围:租户级与指定 compartment

默认情况下,oci.bucket 策略会在整个租户内所有 compartment 中查询桶(源码中通过 ResourceSearchClient 汇总 compartment 列表)。如果需要限定范围,可设置 OCI_COMPARTMENTS 环境变量,多个 compartment OCID 用逗号分隔(详见 bucket_query_storage.rst 与 constants.py 中的 COMPARTMENT_IDS = "OCI_COMPARTMENTS"):

export OCI_COMPARTMENTS=ocid1.test.oc1..<unique_ID>EXAMPLE1-compartmentId-Value,ocid1.test.oc1..<unique_ID>EXAMPLE2-compartmentId-Value

四、测试与验证:仓库如何证明这条策略有效

仓库为桶的可见性整改提供了完整的测试与回放证据。

1. 单元测试用例

在 tests/test_object_storage.py 中,test_change_public_bucket_to_private 与 test_update_public_bucket_to_private 两条用例与本文策略高度一致:

policy = test.load_policy(
    {
        "name": "change-public-bucket-to-private",
        "resource": "oci.bucket",
        "query": [{"namespace_name": namespace_name}],
        "filters": [{"type": "value", "key": "name", "value": bucket_name}],
        "actions": [{"type": "update", "public_access_type": "NoPublicAccess"}],
    },
    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["public_access_type"], "NoPublicAccess")

测试通过 _fetch_bucket_validation_data 在动作执行后调用 get_bucket 回读桶的最新属性,并断言 public_access_type 已变为 NoPublicAccess——这正是"整改后可验证"的最佳实践:先跑策略,再回查状态,确认整改真正生效。

2. Terraform 测试底座

测试使用 terraform/object_storage/bucket.tf 预置测试桶,其初始状态恰为公开:

resource "oci_objectstorage_bucket" "test_bucket" {
  compartment_id = var.OCI_COMPARTMENT_ID
  namespace      = data.oci_objectstorage_namespace.ns.namespace
  name           = "test_bucket"
  access_type    = "ObjectRead"
  auto_tiering   = "Disabled"
  freeform_tags  = { "Project" = "CNCF" }
}

access_type = "ObjectRead" 表明测试桶初始为允许匿名读取的公开桶,与"将公开桶整改为私有"的场景完全吻合。

3. 请求回放(VCR Cassettes)

测试目录下的 TestObjectStorage.test_change_public_bucket_to_private.yml 完整记录了底层 API 调用序列:

  1. GET .../n/<namespace>/b?compartmentId=...&fields=tags —— 枚举桶(携带 tags 字段);
  2. POST .../n/<namespace>/b/test_bucket —— 即 update_bucket 调用,响应中 publicAccessType: NoPublicAccess;
  3. GET .../n/<namespace>/b/test_bucket —— 回读验证,响应同样为 publicAccessType: NoPublicAccess。

从回放可见,public_access_type 在 HTTP 层面对应 publicAccessType 字段,整改动作最终落为一次对桶的 POST 更新请求。

五、扩展实战:先打标、后整改的完整治理闭环

示例文档中的策略假设桶上已有 public_access: 'true' 标签。如果尚未打标,可以先用另一条策略为公开桶自动打标(见 bucket_tagpublic_storage.rst):

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'

这条策略使用了 attributes 过滤器(注册于 object_storage.py 的 AttributesValueFilter):由于桶列表枚举只携带 tags,attributes 过滤器会对候选桶逐个调用 get_bucket 补齐完整属性(包括 public_access_type),再基于 public_access_type = ObjectRead 精准命中"实际公开"的桶,并打上 public_access: 'true' 标签。

由此可以组合出完整的治理闭环:

  1. 盘点打标:运行 tag-public-buckets,让所有 public_access_type = ObjectRead 的桶自动获得 public_access: 'true' 标签;
  2. 整改收口:运行本文的 set-private-bucket,把所有带该标签的桶切换为 NoPublicAccess;
  3. 复核验证:通过 attributes 过滤器重新扫描,确认不再存在 ObjectRead 的公开桶。

此外,若整改后需要清理冗余标签,还可以使用 remove-tag 动作(object_storage.py),例如:

actions:
  - type: remove-tag
    freeform_tags: ['public_access']

六、注意事项

  • 标签依赖:freeform_tags.public_access 的值过滤要求桶已存在该标签,且值精确等于字符串 'true'。若桶标签缺失或值不同(如 True、1),需先通过打标策略统一标签口径;
  • 权限要求:执行 update 动作需要调用 OCI update_bucket 接口,请确保运行 Cloud Custodian 的账号/实例主体拥有对应 Object Storage 管理权限(如 OBJECT_STORAGE_BUCKET_UPDATE 类权限);
  • public_access_type 取值:仓库测试与 Terraform 底座中出现的取值为 ObjectRead(公开读)与 NoPublicAccess(私有),实际可用的取值集合以 OCI Object Storage 服务定义为准;
  • 范围控制:未设置 OCI_COMPARTMENTS 时策略默认扫描整个租户,建议生产环境中显式限定 compartment,避免误伤范围外的桶;
  • 动作容错:update 等 OCI 动作继承自 OCIBaseAction(actions/base.py),支持 fail_on_error(默认 true,失败即抛出异常)与 block_until_completion 等通用参数,可在策略中按需调整失败处理行为。

七、小结

本文基于 bucket_access_storage.rst 示例,完整讲解了"按标签筛选 OCI 公开桶 → 通过 update 动作切换为 NoPublicAccess"这一典型治理场景:在策略层面理解了 resource / filters / actions 三段式写法,在源码层面厘清了 list_buckets 枚举、update_bucket 调用与标签合并逻辑,并通过测试用例与 VCR 回放确认了整改结果可验证。配合 tag-public-buckets 打标策略与 OCI_COMPARTMENTS 范围控制,即可构建一套可自动化的 OCI 对象存储公开访问治理体系。

登录后查看全文
cloud-custodian