云原生运维安全【免费下载链接】cloud-custodianRules engine for cloud security, cost optimization, and governance, DSL in yaml for policies to query, filter, and take actions on resources项目地址https://gitcode.com/gh_mirrors/cl/cloud-custodian点击查看免费下载本指南围绕 OCIOracle Cloud Infrastructure计算实例的“批量启动”场景展开通过一条 Cloud Custodian 策略筛选出所有处于STOPPED状态、且带有custodian_dev自由格式标签的实例并统一执行启动动作。读完本文你将掌握oci.instance资源的查询与过滤写法、start动作的用法以及从安装认证到运行验证、再到源码原理的完整链路。场景背景为什么需要“按标签批量启动”在 OCI 云环境中开发环境的实例常被批量停机以节省成本或在夜间被统一关闭。当开发周期开始时运维人员又需要将这些实例重新拉起。逐个手动启动效率低且容易遗漏而 Cloud Custodian 提供了一种声明式的 YAML 策略 DSL领域专用语言可以查询 → 过滤 → 执行动作一气呵成。本文对应的官方示例文档位于 docs/source/oci/examples/instance_start_dev_instances_compute.rst其核心思路是利用 OCI 实例的自由格式标签freeform tags作为该实例属于开发环境的标记再结合实例生命周期状态lifecycle state过滤最后批量执行启动。核心策略启动所有带 custodian_dev 标签的已停止实例示例文档给出了如下完整策略policies: - name: start-all-stopped-dev-instances description: | Start all the stopped dev instances resource: oci.instance filters: - type: value key: lifecycle_state value: STOPPED op: eq - type: value key: freeform_tags.custodian_dev value: true actions: - start逐段拆解这条策略字段取值含义namestart-all-stopped-dev-instances策略名称运行后会在输出目录下生成同名子目录存放日志与资源 JSON 文件resourceoci.instance声明操作 OCI 计算实例资源由 OCI Provider 的Instance资源类注册见下文源码解析filters[0]value过滤器匹配lifecycle_state等于STOPPED的实例op: eq显式声明相等比较filters[1]value过滤器使用点号路径freeform_tags.custodian_dev读取实例自由格式标签字典中的键custodian_dev要求其值等于字符串trueactionsstart对过滤后命中实例执行启动动作对应 OCI SDK 的instance_action(..., actionSTART)调用需要特别注意的是两点标签键的嵌套访问OCI 实例资源中的freeform_tags是一个键值字典Cloud Custodian 的value过滤器继承自 c7n 核心的ValueFilter支持用点号路径深入字典取值因此freeform_tags.custodian_dev实际读取的是{custodian_dev: true}中的值。值的类型YAML 中true带引号表示字符串。在 OCI 控制台或 CLI 打标签时若标签值写入的是布尔或字符串务必与策略中的字面量保持一致否则过滤器不会命中。前置准备安装与认证本策略运行在 Cloud Custodian 的 OCI ProviderBeta之上完整安装与认证说明见 docs/source/oci/gettingstarted.rst。安装 c7n 与 c7n-ociOCI 插件是可选的独立包需先安装基础 Cloud Custodian要求运行在受支持的 Python 版本上再安装 OCI Providerpip install c7n pip install c7n-oci若希望从当前仓库源码安装最新版可进入仓库后执行pip install -e ./cloud-custodian pip install -e ./cloud-custodian/tools/c7n_ociOCI Provider 包的工程配置见 tools/c7n_oci/pyproject.toml包名为c7n_oci当前版本 0.1.27要求 Python3.9.2依赖c7n与oci2.106,3.0并额外固定pyopenssl24。配置认证凭据Cloud Custodian 在运行时需要能够访问你的 OCI 资源推荐通过 OCI CLI 初始化认证配置oci setup config配置完成后Cloud Custodian 会隐式读取该配置。从源码看tools/c7n_oci/c7n_oci/session.py 中的SessionFactory会按以下优先级构建 OCI 客户端配置若环境变量OCI_FINGERPRINT、OCI_KEY_FILE、OCI_REGION、OCI_TENANCY、OCI_USER全部存在则直接使用环境变量构造配置各变量名定义见 tools/c7n_oci/c7n_oci/constants.py否则若指定了--profile则从 OCI 配置文件读取对应 profile否则读取默认配置DEFAULTprofile。实例主体认证Instance Principal当 Cloud Custodian 直接运行在 OCI 实例上时可以使用实例主体认证只需设置export OCI_CLI_AUTHinstance_principal此时Session.client()会使用InstancePrincipalsSecurityTokenSigner签名器并从签名器获取tenancy_id与region。运行策略与验证输出将策略保存为 YAML 文件例如custodian.yml然后执行custodian run --output-dir. custodian.yml成功执行时命令行会输出类似下面的日志示例来自 docs/source/oci/gettingstarted.rst 中的运行记录2023-05-25 18:15:53,132: custodian.oci.session:INFO Successfully authenticated user ... 2023-05-25 18:15:59,178: custodian.oci.query:INFO List of compartment IDs fetched using the ResourceSearchClient: {ocid1.test.oc1..unique_IDEXAMPLE-compartmentId-1-Value, ocid1.test.oc1..unique_IDEXAMPLE-compartmentId-3-Value} 2023-05-25 18:16:01,118: custodian.policy:INFO policy:filter-for-compute-name resource:oci.instance region: count:1 time:7.98 2023-05-25 18:16:05,474: custodian.oci.resources.compute:INFO Received status 200 for PUT:update_instance ...针对start动作源码 tools/c7n_oci/c7n_oci/resources/compute.py 会记录类似Received status 200 for POST:START的日志标识 OCI 计算服务的启动请求已受理。运行结束后--output-dir下会生成以策略名命名的目录内含日志与描述命中资源的 JSON 文件。控制查询范围OCI_COMPARTMENTS默认情况下策略会针对租户tenancy内所有包含该类资源的 compartment 执行查询。你可以通过OCI_COMPARTMENTS环境变量指定一个或多个 compartment多个 OCID 用逗号分隔export OCI_COMPARTMENTSocid1.test.oc1..unique_IDEXAMPLE-compartmentId-2-Value,ocid1.test.oc1..unique_IDEXAMPLE-compartmentId-3-Value这一行为在源码中有直接体现QueryResourceManager.source_type属性tools/c7n_oci/c7n_oci/query.py会判断——若设置了OCI_COMPARTMENTS则使用describe-native源逐 compartment 调用list_instances否则使用describe-search源先通过ResourceSearchClient发现资源所在的 compartment再逐 compartment 拉取完整资源。两种源都会以(tenancy, region, resource, compartment_id, query)为缓存键做结果缓存。从源码理解 start 动作的底层实现资源注册oci.instancecompute.py 中Instance类通过resources.register(instance)注册为oci.instance其resource_type声明了service oci.core、client ComputeClient使用 OCI Python SDK 的 Compute 客户端enum_spec (list_instances, items[], None)枚举资源时调用list_instancesid id、name display_name资源的唯一标识与展示名search_resource_type instance用于describe-search源的结构化搜索。InstanceStart 动作start动作注册于 compute.pyInstance.action_registry.register(start) class InstanceStart(OCIBaseAction): schema type_schema(start, rinheritOCIBaseAction.schema) def perform_action(self, resource): client self.manager.get_client() response client.instance_action( instance_idresource[id], actionSTART, ) log.info(fReceived status {response.status} for POST:START {response.request_id}) return response即对每个命中资源调用 OCI SDK 的instance_action传入instance_id即资源的id字段与动作START。同一文件还注册了同族的stopSOFTSTOP/ 强制STOP与rebootSOFTRESET/ 强制RESET动作可参见 instance_poweron_compute.rst 中启动单个已停止实例的对照示例。OCIBaseAction 的通用行为所有 OCI 动作继承自 tools/c7n_oci/c7n_oci/actions/base.py 的OCIBaseAction其 schema 额外支持两个通用选项参数类型说明fail_on_errorboolean默认 true动作执行失败时是否抛出异常设为 false 时会把失败资源记入failed_resources并从处理列表中移除block_until_completionboolean是否开启批处理模式等待动作完成process()会逐个资源调用子类实现的perform_action(resource)并汇总succeeded_resources与failed_resources结果。测试验证仓库如何保证该功能可靠仓库在 tools/c7n_oci/tests/test_instance.py 中提供了test_instance_start测试用例terraform(compute, scopeclass) def test_instance_start(self, test, compute): ocid self._get_instance_details(compute) session_factory test.oci_session_factory() policy test.load_policy( { name: instance-start, resource: oci.instance, filters: [ {type: value, key: id, value: ocid}, ], actions: [{type: start}], }, session_factorysession_factory, ) policy.run() resource self._fetch_instance_validation_data(policy.resource_manager, ocid) test.assertEqual(resource[id], ocid) assert resource[lifecycle_state] in [STARTING, RUNNING]该测试通过 Terraform 编排真实的计算实例运行按 id 过滤 start 动作的策略随后校验实例生命周期状态进入STARTING或RUNNING从而证明start动作确实触发了实例启动。对应的 VCR 录制数据位于tools/c7n_oci/tests/cassettes/TestInstance.test_instance_start.yml。这也意味着本文示例策略中使用的lifecycle_state过滤器取值STOPPED与 OCI 实例生命周期枚举中的状态值保持一致。组合建议与注意事项与其他过滤条件组合除了按标签与状态过滤还可以组合display_name见 gettingstarted.rst 示例一、shape示例二等字段或通过策略级query关键字在查询阶段先行收窄范围例如query: [{lifecycle_state: STOPPED}]。先 dry-run 再执行可以把actions先注释掉运行一次从输出目录的 JSON 中确认命中实例集合避免误启动生产实例也可以将标签改为更严格的值如custodian_dev: true与部门标签联合使用。关注 Beta 状态OCI Provider 目前标注为 Beta相关能力以 docs/source/oci/gettingstarted.rst 与仓库源码为准生产环境使用前建议先在测试租户验证。多 compartment 的执行范围不设置OCI_COMPARTMENTS时查询覆盖整个租户可能命中大量资源建议结合MaxResourceLimit或先以单个 compartment 验证。通过本文的策略与源码解析你已经可以从零搭建一条按标签批量启动 OCI 开发实例的自动化治理策略并可在此基础上自由组合其他过滤条件与动作stop、reboot、update、remove-tag等实现完整的实例生命周期治理。赞分享云原生运维安全【免费下载链接】cloud-custodianRules engine for cloud security, cost optimization, and governance, DSL in yaml for policies to query, filter, and take actions on resources项目地址https://gitcode.com/gh_mirrors/cl/cloud-custodian点击查看免费下载相关推荐Cloud Custodian OCI 实战查询并批量移除计算实例标签oci.instance remove-tagCloud Custodian OCI 实战查询并批量移除计算实例标签oci.instance remove tag 本文基于 Cloud Custodi云原生运维安全Cloud Custodian OCI 实战用 reboot 动作重启 Compute 实例Cloud Custodian OCI 实战用 reboot 动作重启 Compute 实例 本文基于 Cloud Custodianc7nOCI 插件的云原生运维安全Cloud Custodian 实战用 ec2-invalid-ami 策略自动停止使用未批准 AMI 的 EC2 实例Cloud Custodian 实战用 ec2 invalid ami 策略自动停止使用未批准 AMI 的 EC2 实例 本文基于 Cloud Custodi云原生运维安全创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
阅读完成 · 觉得有帮助?