Terraform Deployment Patterns for AWS WAF v2 Security Automation

Building a production-ready web application firewall with Terraform requires precise control over Web ACLs, rule groups, logging, and IAM automation. AWS WAF v2 provides the protective primitives while Terraform provides versioned, repeatable infrastructure delivery. The patterns below synthesize deployment of the Security Automations for AWS WAF solution with Terraform and hands-on Web ACL construction.

Prerequisites and Tooling

Before starting any WAF automation, the baseline tooling must be in place.

Terraform version 1.1.9 or later, installed and configured
AWS Command Line Interface version 2.4.25 or later, installed and configured with necessary permissions
An active AWS account

The Security Automations for AWS WAF solution can be deployed by using AWS CloudFormation according to the Security Automations for AWS WAF Implementation Guide. The Terraform pattern provides an alternative deployment option for organizations that use HashiCorp Terraform as their preferred infrastructure as code tool to provision and manage cloud infrastructure.

Component Requirement
IaC tool Terraform 1.1.9+
CLI AWS CLI 2.4.25+
Account Active AWS account with IAM permissions
Scope REGIONAL for ALB/API Gateway, CLOUDFRONT for CloudFront distributions

When you deploy this solution, Terraform automatically applies the changes in the cloud and deploys and configures the AWS WAF settings and protective features.

Architecture Overview of Security Automations

The target architecture deploys the Security Automations for AWS WAF solution. The pattern is designed for organizations without dedicated security teams who need customizable rules deployed in web access control lists.

When you run terraform apply, Terraform does the following:

  • Terraform creates AWS Identity and Access Management roles and Lambda functions based on the inputs from the testing.tfvars file
  • Terraform creates AWS WAF ACL rules and IP sets based on the inputs from the testing.tfvars file
  • Terraform creates Amazon Simple Storage Service buckets, Amazon EventBridge rules, AWS Glue database tables, and Amazon Athena work groups based on the inputs from the testing.tfvars file
  • Terraform deploys the AWS CloudFormation stack to provision the custom resources
  • Terraform creates the Amazon API Gateway resources based on the given inputs from testing.tfvars file

Automation and scale are achieved by using this pattern to create AWS WAF rules for multiple AWS accounts and AWS Regions to deploy the Security Automations for AWS WAF solution throughout your AWS Cloud environment.

Tools referenced in the pattern include AWS services and other services. The code for this pattern is available in the GitHub AWS WAF Automation Using Terraform repository.

Core Web ACL Construction with Terraform

AWS WAF lets you control HTTP and HTTPS traffic that reaches your web applications. You can block SQL injection attempts, cross-site scripting, bad bots, and other common attack patterns. Managing WAF rules with Terraform means your web application firewall configuration is version-controlled, reviewed, and applied consistently across all your endpoints.

The Web ACL is the container for all your WAF rules. Start with a default action and add rules:

hcl resource "aws_wafv2_web_acl" "main" { name = "${var.project}-waf" description = "WAF rules for ${var.project}" scope = "REGIONAL" default_action { allow {} } visibility_config { cloudwatch_metrics_enabled = true metric_name = "${var.project}-waf-metrics" sampled_requests_enabled = true } tags = { Name = "${var.project}-waf" Environment = var.environment } }

Scope is REGIONAL for regional resources and CLOUDFRONT for CloudFront distributions with a us-east-1 provider. Visibility config enables CloudWatch metrics and sampled requests for the entire Web ACL.

For API Gateway protection, a typical association looks like:

hcl web_acl_id = aws_wafv2_web_acl.main.arn

Managed Rule Groups and Custom Rule Statements

AWS provides managed rule groups that cover the most common attack patterns.

Add AWS Managed Rule Groups:

hcl resource "aws_wafv2_web_acl" "main" { # ... }

A modular implementation using the terraform-aws-modules/wafv2/aws module demonstrates comprehensive rule support:

hcl module "wafv2" { source = "terraform-aws-modules/wafv2/aws" name = "my-web-acl" scope = "REGIONAL" default_action = "allow" rules = { common-rule-set = { priority = 1 override_action = "none" statement = { managed_rule_group_statement = { name = "AWSManagedRulesCommonRuleSet" vendor_name = "AWS" } } } rate-limit = { priority = 2 action = "block" statement = { rate_based_statement = { limit = 1000 } } } } tags = { Environment = "dev" Terraform = "true" } }

The module provides full coverage of AWS provider WAFv2 surface: every WAFv2 resource is supported by the root module or a submodule. AWS WAF v2 Web ACL with comprehensive rule statement support is available.

Statement types supported include:

  • byte match
  • geo match
  • IP set reference
  • label match
  • managed rule group
  • rate based
  • regex match
  • regex pattern set reference
  • rule group reference
  • size constraint
  • SQLi match
  • XSS match

Compound statements AND, OR, NOT with 2 levels of nesting, including AND/OR inside scopedownstatement are supported. Dual-mode actions are supported as simple string allow, block, count, captcha, challenge or objects with custom response/request handling with custom response bodies.

CAPTCHA and challenge configuration is available. Association configuration for request body size limits is supported. Optional inline Web ACL associations and optional inline logging configuration are provided. Submodules exist for IP sets, regex pattern sets, Web ACL associations, logging configuration, custom rule.

Logging and Observability Configuration

Enable WAF Logging for security analysis:

hcl resource "aws_wafv2_web_acl_logging_configuration" "main" { log_destination_configs = [aws_cloudwatch_log_group.waf.arn] resource_arn = aws_wafv2_web_acl.main.arn logging_filter { default_behavior = "DROP" filter { behavior = "KEEP" requirement = "MEETS_ANY" condition { action_condition { action = "BLOCK" } } condition { action_condition { action = "COUNT" } } } } }

Log group must start with aws-waf-logs-:

hcl resource "aws_cloudwatch_log_group" "waf" { name = "aws-waf-logs-${var.project}" retention_in_days = 90 }

Only log blocked and counted requests to reduce volume. Logging filter with default_behavior DROP and KEEP for BLOCK and COUNT actions is a recommended pattern.

Environment Modularization and API Gateway Integration

During implementation, we configured WAF, IAM roles, and CloudWatch Logs using Terraform, and this article serves as a memorandum of the process.

Benefits of implementing AWS WAF:

  • It can protect web applications from common web attacks
  • It allows for the efficient application of security rules using AWS-managed rule sets
  • It offers flexible security measures by allowing specific rules to be overridden

The directory structure of Terraform is modularized, with configurations separated for each environment dev, stg, prod. In practice, AWS WAF is implemented in front of API Gateway with modular Terraform separating WAF, IAM, and logging.

Best practices from the pattern include:

  • Put static files in separate Amazon S3 buckets
  • Avoid hardcoding variables
  • Limit the use of custom scripts
  • Adopt a naming convention

Multi-Account Scaling and Operational Guidance

AWS WAF with Terraform gives you a layered defense for your web applications. Start with the AWS managed rule groups to cover the most common attack patterns, add rate limiting for abuse prevention, and build custom rules for your specific application needs.

The key is to start in count mode monitoring only so you can tune rules before blocking traffic. Once you are confident in your rules, switch to block mode and enable logging for ongoing security monitoring.

The pattern enables creating AWS WAF rules for multiple AWS accounts and AWS Regions to deploy the Security Automations for AWS WAF solution throughout your AWS Cloud environment.

Conclusion

Terraform driven AWS WAF v2 deployment unifies security policy with infrastructure as code. The Security Automations for AWS WAF solution provides a pre-architected foundation that Terraform instantiates with IAM roles, Lambda functions, WAF ACL rules, IP sets, S3 buckets, EventBridge rules, Glue tables, Athena workgroups, and API Gateway resources. Core Web ACL construction centers on default actions, visibility config, and tags with REGIONAL or CLOUDFRONT scope.

Managed rule groups deliver immediate coverage for common attacks while module-based rule definitions allow rate limiting, byte match, geo match, IP set reference, label match, regex match, SQLi match, XSS match, and compound AND/OR/NOT statements with dual-mode actions including captcha and challenge. Logging configuration with CloudWatch Log Groups prefixed aws-waf-logs- and filtered logging for BLOCK and COUNT actions provides auditable observability.

Operational maturity comes from environment modularization for dev, stg, prod, count mode tuning before block enforcement, naming conventions, and avoidance of hardcoded variables. Together these patterns produce version-controlled, reviewable, consistently applied web application firewall posture across accounts and regions.

Sources

  1. Deploy the Security Automations for AWS WAF solution by using Terraform
  2. How to Implement WAF Rules With Terraform
  3. AWS WAF Implementation Guide Setting Up With Terraform For Enhanced Security
  4. Terraform module which creates AWS WAF v2 Web ACL resources with comprehensive rule support

Related Posts