Search code examples
amazon-web-servicescloudcustodian

Cloud Custodian policy to stop EC2 instances containing a tag and not containing a tag value


I want to stop EC2 instances which do not have a tag ABC and whose tag(ABC) value is not of type @gmail.com

I am trying to use the cloud custodian policy in AWS, I have written like this

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

However, this code does not have the desired effect. Any idea why?


Solution

  • Created this policy using special filters example.

    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).)*$'
    

    You can test out this filter using python's re module.

    $ 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'