Terraform-Driven AWS WAF Security Automation and Rule Management

AWS WAF is a web application firewall that helps protect applications from common exploits by using customizable rules, which you define and deploy in web access control lists (ACLs). Configuring AWS WAF rules can be challenging, especially for organizations that do not have dedicated security teams. To simplify this process, Amazon Web Services offers the Security Automations for AWS WAF. The Security Automations for AWS WAF solution can be deployed by using AWS CloudFormation according to the instructions in the Security Automations for AWS WAF Implementation Guide. This pattern provides an alternative deployment option for organizations that use HashiCorp Terraform as their preferred infrastructure as code (IaC) tool to provision and manage their cloud infrastructure. When you deploy this solution, Terraform automatically applies the changes in the cloud and deploys and configures the AWS WAF settings and protective features.

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 guide covers building a complete WAF configuration with Terraform, from AWS managed rule groups to custom rules tailored to your application.

Prerequisites and Tooling for Terraform Deployment

Deploying the Security Automations for AWS WAF solution with Terraform requires specific tool versions and permissions.

  • An active AWS account.
  • AWS Command Line Interface (AWS CLI) version 2.4.25 or later, installed and configured with necessary permissions. For more information, see Getting started (AWS CLI documentation).
  • Terraform version 1.1.9 or later, installed and configured. For more information, see Install Terraform (Terraform documentation).

The pattern deploys the Security Automations for AWS WAF solution. For more information about the target architecture, see Architecture overview in the Security Automations for AWS WAF Implementation Guide.

Requirement Minimum Version / Condition
AWS Account Active
AWS CLI 2.4.25 or later
Terraform 1.1.9 or later

Architecture and Automation Scope

The Terraform deployment for the Security Automations for AWS WAF solution automates multiple AWS services in a single apply.

When you run terraform apply, Terraform does the following:

  • Terraform creates AWS Identity and Access Management (IAM) 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 the Amazon Simple Storage Service (Amazon S3) 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.

For more information about the AWS Lambda automations in this deployment, the Application log parser, the AWS WAF log parser, the IP lists parser, and the Access handler, see Component details in the Security Automations for AWS WAF Implementation Guide.

You can use 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.

The code for this pattern is available in the GitHub AWS WAF Automation Using Terraform.

Best practices associated with the pattern include:

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

Core Web ACL Construction with Terraform

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" # Use CLOUDFRONT for CloudFront distributions with a us-east-1 provider default_action { allow {} } # Visibility config for the entire Web ACL visibility_config { cloudwatch_metrics_enabled = true metric_name = "${var.project}-waf-metrics" sampled_requests_enabled = true } tags = { Name = "${var.project}-waf" Environment = var.environment } }

AWS provides managed rule groups that cover the most common attack patterns. Adding AWS Managed Rule Groups is a primary step in building a baseline defense.

Managed Rule Groups and API Gateway Integration

To enhance the security of our application, we have implemented AWS WAF in front of API Gateway. During the implementation, we configured WAF, IAM roles, and CloudWatch Logs using Terraform.

Here are the 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.

A modular Terraform project for this use case separates configurations per environment and per concern.

Path Contents
terraform-project/environments/dev/ backend.tf, main.tf
terraform-project/environments/stg/ backend.tf, main.tf
terraform-project/environments/prod/ backend.tf, main.tf
terraform-project/modules/waf/ main.tf, variables.tf, outputs.tf, provider.tf, README.md
terraform-project/modules/iam_roles/ main.tf, variables.tf, outputs.tf, provider.tf, README.md
terraform-project/modules/cloudwatch_logs/ main.tf, variables.tf, outputs.tf, provider.tf, README.md

The following Terraform code applies WAF to API Gateway and sets various security rules.

hcl resource "aws_wafv2_web_acl" "api_gateway_waf" { name = "api-gateway-waf" description = "Managed rule WAF" scope = "REGIONAL" default_action { allow {} } rule { name = "AWS-AWSManagedRulesCommonRuleSet" priority = 0 override_action { none {} } statement { managed_rule_group_statement { name = "AWSManagedRulesCommonRuleSet" vendor_name = "AWS" rule_action_override { action_to_use { allow {} } name = "SizeRestrictions_BODY" } } } visibility_config { cloudwatch_metrics_enabled = true metric_name = "AWS-AWSManagedRulesCommonRuleSet" sampled_requests_enabled = true } } rule { name = "AWS-AWSManagedRulesAmazonIpReputationList" priority = 1 override_action { none {} } statement { managed_rule_group_statement { name = "AWSManagedRulesAmazonIpReputationList" vendor_name = "AWS" } } visibility_config } }

The directory structure of Terraform is modularized, with configurations separated for each environment (dev, stg, prod). The modules directory contains Terraform modules (waf, iamroles, cloudwatchlogs, etc.) used in the project.

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 # Only log blocked and counted requests to reduce volume 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 }

Visibility configuration for the Web ACL enables CloudWatch metrics and sampled requests.

Operational Guidance and Patterns

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.

For related security topics, see how to implement DDoS protection with Terraform and how to implement security groups best practices with Terraform.

The pattern is authored by Dr. Rahul Sharad Gaikwad and Tamilselvan P, Amazon Web Services.

Conclusion

Deploying AWS WAF through Terraform provides repeatable, auditable, and scalable protection for web applications and API Gateway endpoints. The Security Automations for AWS WAF solution demonstrates how Terraform can orchestrate IAM roles, Lambda functions, S3 buckets, EventBridge rules, Glue tables, Athena work groups, CloudFormation stacks, API Gateway resources, and WAF ACL rules from a single testing.tfvars input. Building a base Web ACL with a default allow action, visibility configuration, and managed rule groups such as AWSManagedRulesCommonRuleSet and AWSManagedRulesAmazonIpReputationList establishes immediate coverage for common exploits.

Modularization by environment and by concern, as shown with separate environments for dev, stg, and prod and modules for waf, iamroles, and cloudwatchlogs, supports safe promotion and consistent naming. Logging configuration with aws-waf-logs- prefixed log groups, retention policies, and filters that keep BLOCK and COUNT actions while dropping the rest enables cost-effective security monitoring. Starting rules in count mode, reviewing metrics, and then moving to block mode aligns with best practices for tuning without business impact. Together, these practices deliver version-controlled WAF rules that can be extended across multiple accounts and regions.

Sources

  1. https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/deploy-the-security-automations-for-aws-waf-solution-by-using-terraform.html
  2. https://oneuptime.com/blog/post/2026-02-23-how-to-implement-waf-rules-with-terraform/view
  3. https://dev.to/suzuki0430/aws-waf-implementation-guide-setting-up-with-terraform-for-enhanced-security-3ba5

Related Posts