利用custodian实现自动修复

Cloud Custodian

Cloud Custodian 是一个开源工具,使用python编写。组织可以通过使用Custodian管理云环境。支持 AWS、Azure、GCP、Oracel、Tencent Cloud。Custodian 遵循 "合规即代码 "原则,因此您可以验证、模拟运行和审查策略变更。

Cloud Custodian 策略使用 YAML 格式,包括以下内容:

  • 运行策略的资源类型

  • 筛选器可缩小资源集的范围

  • 对筛选出的资源采取的行动

安装Cloud Custodian

编写策略

假设编写的策略名称为ec2-tag-compliance-mark.yml,用于给缺少指定标签的EC2打上标签。此处检查EC2实例缺少标签Owner,CostCenter,Project的其中一个,则自动给打上Owner: Lily Chen, Project:SOAR的标签。

policies:

- name: ec2-tag-compliance-mark
  resource: ec2
  comment: |
    Find all (non-ASG) instances that are not conformant
    to tagging policies, and tag them.
  filters:
    - or:
        - "tag:Owner": absent
        - "tag:CostCenter": absent
        - "tag:Project": absent
  actions:
      - type: tag
        key: Owner
        value: Lily Chen
      - type: tag
        key: Project
        value: SOAR

部署策略

使用AWS CLI,在本地电脑上配置并部署好AWS CLI,之后就可以开始部署策略了

# 验证策略是否正确 (note this happens by default on run)
custodian validate ec2-tag-compliance-mark.yml

# 试运行策略 (no actions executed) 查看会影响哪些资源
# match each policy.
custodian run --dryrun -s out ec2-tag-compliance-mark.yml

# 运行策略
custodian run -s out ec2-tag-compliance-mark.yml

如果需要在所有region都执行策略,则需要加上--region all:

custodian run -s out --region all policy.yml

最后更新于