amazon-web-servicesaws-cloudformationamazon-wafamazon-alb

How to add AWS WAF to an ALB via CloudFormation


I can't find any examples or documentation on how to associate a WAF with an ALB via CloudFormation. Supposedly its possible going by this news announcement https://aws.amazon.com/about-aws/whats-new/2017/05/cloudformation-support-for-aws-waf-on-alb/ but there isn't anything I've found that shows how. Using CloudFront instead of ALB is well documented but I haven't found a single example with regard to using an ALB (via CloudFormation).

Update: I dont need a full example that does the entire setup for me but at least a snippet that points out how the WAF will know to associate with the ALB or vice versa. The linking is whats missing.


Solution

  • To solve this I browsed through their release history and found the CloudFormation resources that were updated to support WAF & ALB http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/ReleaseHistory.html From there I was able to deduce that the linking component is a WebACLAssociation that maps WAF and ALB. But this also requires that instead of a normal WebACL you must use the WAFRegional. So far it seems to only mean changing ::WAF to ::WAFRegional throughout your code.

    WAFRegional (AWS::WAFRegional::WebACL): http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-webacl.html

    "MyWebACL": {
      "Type": "AWS::WAFRegional::WebACL",
      "Properties": {
        "Name": "WebACL to with three rules",
        "DefaultAction": {
          "Type": "ALLOW"
        },
        "MetricName" : "MyWebACL",
        "Rules": [
          {
            "Action" : {
              "Type" : "BLOCK"
            },
            "Priority" : 1,
            "RuleId" : { "Ref" : "MyRule" }
          },
          {
            "Action" : {
              "Type" : "BLOCK"
            },
            "Priority" : 2,
            "RuleId" : { "Ref" : "BadReferersRule" }
          },
          {
            "Action" : {
              "Type" : "BLOCK"
            },
            "Priority" : 3,
            "RuleId" : { "Ref" : "SqlInjRule" }
          }
        ]
      }      
    }
    

    WebACLAssociation (AWS::WAFRegional::WebACLAssociation) http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-webaclassociation.html

        "MyWebACLAssociation": {
      "Type": "AWS::WAFRegional::WebACLAssociation",
      "Properties": {
        "ResourceArn": { "Ref": "MyLoadBalancer" },
        "WebACLId": { "Ref": "MyWebACL" }
      }
    }