You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Cloud Custodian EC2策略mark-for-op动作不生效问题咨询

Cloud Custodian EC2自动终止策略mark-for-op动作不触发排查方案

问题说明

配置Cloud Custodian自动化运维策略实现EC2实例满足条件后达到指定时长自动终止功能时,过滤器、periodic运行模式均正常生效,仅actions字段下的mark-for-op打标动作始终未触发。
原策略配置如下:

Policy:
policies:
  - name: ec2-terminate-instance
    resource: ec2
    description: |
      Mark any stopped ec2 instance for deletion in 60 days
      If an instance has not been started for 60 days or over
      then they will be deleted similar to internal policies as it wont be patched.
    filters:
      - "tag:expiration": present
      - "State.Name": stopped
    mode:
      schedule: "rate(15 minutes)"
      type: periodic
      role: arn:aws:iam::xxxxxxxxxxxx:role/cloud-custodian-role
    actions:
      - type: mark-for-op
        tag: c7n_stopped_instance
        op: terminate
        hours: 0.5

策略预期逻辑:筛选携带expiration标签、处于stopped状态的EC2实例,通过mark-for-op动作打标,配置0.5小时后自动执行terminate终止操作。

排查思路与修复步骤

  • 修复YAML语法错误:原配置最开头冗余无效顶层键Policy:,且下方policies数组未做正确缩进,会导致策略加载阶段动作段解析异常。需要删除冗余行,保证所有策略字段缩进符合YAML规范。
  • 校验执行角色权限:配置中指定的执行角色arn:aws:iam::xxxxxxxxxxxx:role/cloud-custodian-role必须包含ec2:CreateTags、ec2:DescribeTags权限,缺失权限时打标动作会静默失败。可直接查看Custodian运行日志,搜索AccessDenied关键字确认权限问题,按需给角色附加对应权限即可。
  • 补全mark-for-op配套逻辑:mark-for-op本身仅负责打存储操作时间的标签,不会自动触发后续终止操作,必须额外配置第二条策略,通过marked-for-op过滤器识别到期的标记实例,才会真正执行终止动作。原配置仅编写了打标策略,缺失后续执行逻辑,就算打标成功也不会自动终止实例。
  • 优化重复打标问题:在打标策略的过滤器中增加"tag:c7n_stopped_instance": absent规则,避免每次周期运行都重复给已经打过标的实例覆盖标签,导致到期时间被不断重置。
  • 校验调度周期匹配度:当前配置的标记等待时长为0.5小时(30分钟),策略调度周期为15分钟,保证调度周期小于等待时长即可,避免出现漏扫到期实例的问题。

修正后可用完整配置

policies:
  # 策略1:给符合条件的已停止实例打终止标记
  - name: ec2-mark-stopped-for-terminate
    resource: ec2
    description: 标记携带expiration标签的已停止EC2实例,30分钟后执行终止
    filters:
      - "tag:expiration": present
      - "State.Name": stopped
      - "tag:c7n_stopped_instance": absent
    mode:
      schedule: "rate(15 minutes)"
      type: periodic
      role: arn:aws:iam::xxxxxxxxxxxx:role/cloud-custodian-role
    actions:
      - type: mark-for-op
        tag: c7n_stopped_instance
        op: terminate
        hours: 0.5

  # 策略2:扫描到期标记实例,执行终止操作
  - name: ec2-terminate-marked-stopped-instance
    resource: ec2
    description: 终止达到标记等待时长的已停止EC2实例
    filters:
      - type: marked-for-op
        tag: c7n_stopped_instance
        op: terminate
    mode:
      schedule: "rate(15 minutes)"
      type: periodic
      role: arn:aws:iam::xxxxxxxxxxxx:role/cloud-custodian-role
    actions:
      - terminate

上线前可先执行dry run验证逻辑:运行custodian run --dryrun -s out <策略文件路径>命令,查看输出的执行计划是否匹配预期,确认打标、终止动作都能正确命中目标实例后再正式上线。

内容的提问来源于stack exchange,提问作者rocky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.01 03:45:34