Search code examples
aws-cloudformationamazon-waf

How to allow certain IP set resource with my WAF v2 via cloudformation?


example contrived for this question, based on the aws documentation, I I defined a WAFv2 resource type, a rule and IP set list by using WAF. the following works and it blocks the IP , i specified but how to allow certain IP list and block all others?

Resources:
  
  WebAcl:
    Type: AWS::WAFv2::WebACL
    Properties:
      Name: sample-acl
      Scope: REGIONAL
      Description: sample ACL.
      DefaultAction:
        Allow: {}
      VisibilityConfig:
        SampledRequestsEnabled: true
        CloudWatchMetricsEnabled: true
        MetricName: sample-acl
      Rules:
      - Name: blockIPList
        Priority: 4
        Action:
          Block: {}
        VisibilityConfig:
          SampledRequestsEnabled: true
          CloudWatchMetricsEnabled: true
          MetricName: IPListMetric
        Statement:
          IPSetReferenceStatement:
            Arn: !GetAtt myIPSet.Arn
 myIPSet:
    Type: 'AWS::WAFv2::IPSet'
    Properties:
      Name: sampleIPlistIPv4
      Scope: REGIONAL
      IPAddressVersion: IPV4
      Addresses:
        - 70.25.14.172/32

  

Solution

  • To enable it on a CloudFront distribution

    CloudFront:
    Type: AWS::CloudFront::Distribution
    Properties:
      DistributionConfig:
        WebACLId: !GetAtt ExampleWebACL.Arn
    

    Or for an ALB or API Gateway you can use https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafv2-webaclassociation.html

    Type: AWS::WAFv2::WebACLAssociation
    Properties: 
      ResourceArn: String
      WebACLArn: String
    

    Edit: Did you perhaps mean how you enable you IPSet in your rule group?

    RuleGroup:
    Type: 'AWS::WAFv2::RuleGroup'
    Properties:
      Name: SampleRuleGroup
      Scope: REGIONAL
      Description: SampleRuleGroup
      VisibilityConfig:
        SampledRequestsEnabled: true
        CloudWatchMetricsEnabled: true
        MetricName: SampleRuleGroupMetrics
      Rules:
        - Name: ip-whitelist
          Priority: 0
          Action:
            Allow: { }
          VisibilityConfig:
            SampledRequestsEnabled: true
            CloudWatchMetricsEnabled: true
            MetricName: ip-whitelist-metric
          Statement:
            IPSetReferenceStatement:
              Arn: !GetAtt SampleIPSet.Arn