首页 > 解决方案 > 用于停止包含标签但不包含标签值的 EC2 实例的 Cloud Custodian 策略

问题描述

我想停止没有标签ABCtag(ABC)值不是类型的 EC2 实例@gmail.com

我正在尝试在 AWS 中使用云托管策略,我是这样写的

  filters:
    - or:
      - "tag:ABC": absent
      - type: value
        key: "tag:ABC"
        op: ne
        value: '/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@gmail.com/'
  actions:
    - stop

但是,此代码没有预期的效果。知道为什么吗?

标签: amazon-web-servicescloudcustodian

解决方案


使用特殊过滤器示例创建此策略。

ec2-without-gmail-in-tag.yml

policies:
  - name: ec2-without-gmail-in-tag
    description: |
      Stop EC2 instances that do not have a tag or if the tag exists but doesnt have a specific value
    resource: ec2
    filters:
      - or:
        # check if tag is absent
        - "tag:ABC": absent
        # or check if tag does not contain @gmail.com using a negative lookahead
        - type: value
          key: "tag:ABC"
          op: regex
          value: '^((?!@gmail.com).)*$'

re您可以使用 python 的模块测试此过滤器。

$ python

>>> import re

>>> regex = '^((?!@gmail.com).)*$'

>>> re.match(regex, 'Test if @gmail.com matches').group(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'

>>> re.match(regex, 'Test if @gmail matches').group(0)
'Test if @gmail matches'

推荐阅读