How to block an IP address with AWS WAF and Terraform

Bjorn Krols

Bjorn Krols

Published on
03 November 2021

Convert the IP address into CIDR format:

11.22.333.444 becomes 11.22.333.444/32

Create an IP set with the address:

resource "aws_wafv2_ip_set" "ip_blacklist" {
  name               = "ip-blacklist"
  scope              = "REGIONAL"
  ip_address_version = "IPV4"
  addresses          = ["11.22.333.444/32"]
}

Create a web ACL with the following rule:

resource "aws_wafv2_web_acl" "firewall" {
  name = "firewall"

  scope = "REGIONAL"

  default_action {
    allow {}
  }

  rule {
    name     = "ip-blacklist"
    priority = 1

    action {
      block {}
    }

    statement {
      ip_set_reference_statement {
        arn = aws_wafv2_ip_set.ip_blacklist.arn
      }
    }

    visibility_config {
      cloudwatch_metrics_enabled = true
      metric_name                = "BlacklistedIP"
      sampled_requests_enabled   = true
    }
  }

  visibility_config {
    cloudwatch_metrics_enabled = true
    metric_name                = "Allowed"
    sampled_requests_enabled   = true
  }
}

You can now associate the ACL with an API Gateway REST API, Application Load Balancer, etc...

Subscribe to our newsletter

The latest news, articles, and resources, sent to your inbox weekly.

More like this