Deploying AWS WAF through Terraform moves web application firewall configuration from manual console clicks into version-controlled, peer-reviewed infrastructure. 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 pattern is particularly relevant for the Security Automations for AWS WAF solution. 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 (AWS) 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.
Prerequisites and deployment foundations
Before starting a Terraform deployment for AWS WAF, validate the baseline environment.
Prerequisites
- 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
- AWS Command Line Interface (AWS CLI) installed and configured with necessary permissions.
- Terraform installed and configured.
The Security Automations for AWS WAF solution is developed using Terraform which automatically deploys a set of AWS WAF rules that filter common web-based attacks. Users can select from preconfigured protective features that define the rules included in an AWS WAF web access control list (web ACL). Once deployed, AWS WAF protects your Amazon CloudFront distributions or Application Load Balancers by inspecting web requests.
Typical deployment flow for the automation pattern:
terraform initterraform plan -var-file="testing.tfvars"terraform apply -var-file="testing.tfvars"
The solution uses a modular directory structure, with configurations separated for each environment (dev, stg, prod). The directory structure of Terraform is modularized, with configurations separated for each environment (dev, stg, prod).
Web ACL architecture 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
}
}
The Web ACL resource defines scope as REGIONAL for ALB and API Gateway, or CLOUDFRONT for CloudFront distributions with a us-east-1 provider. Visibility config enables CloudWatch metrics and sampled requests for the entire Web ACL.
Benefits of implementing AWS WAF via Terraform:
- 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.
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.
Managed rule groups and custom rules
AWS provides managed rule groups that cover the most common attack patterns.
Add AWS Managed Rule Groups
AWS provides managed rule groups that cover the most common attack patterns.
A complete WAF configuration with Terraform covers:
- AWS managed rule groups to cover the most common attack patterns
- Custom rules tailored to your application
- Rate limiting for abuse prevention
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.
Rate limiting and IP reputation can be combined with managed rules. For example, the Security Automations pattern exposes parameters such as:
- ActivateHttpFloodProtectionParam = yes - AWS Lambda log parser, yes - Amazon Athena log parser, yes - AWS WAF rate based rule
- ActivateScannersProbesProtectionParam = yes - AWS Lambda log parser, yes - Amazon Athena log parser
- ENDPOINT = ALB , cloudfront
These parameters drive conditional creation of Lambda log parsers, Athena log parsers, and WAF rate based rules.
Logging, observability and supporting resources
Enable WAF Logging
Configure 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
}
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.
Automation and scale
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.
Tools used in the pattern
| Category | Service |
|---|---|
| AWS services | AWS WAF, IAM, Lambda, S3, EventBridge, Glue, Athena, API Gateway, CloudWatch Logs |
| Other services | HashiCorp Terraform, AWS CLI |
| Code repository | The code for this pattern is available in the GitHub AWS WAF Automation Using Terraform |
Automation and scale supports consistent rollout. Terraform will create all resources in the correct order, handling dependencies automatically.
Best practices from the pattern:
- Put static files in separate Amazon S3 buckets.
- Avoid hardcoding variables.
- Limit the use of custom scripts.
- Adopt a naming convention.
Managing AWS resources with Terraform brings consistency, version control, and automation to your infrastructure. The configurations in this guide follow production best practices and can be extended to match your specific requirements.
Always review the plan before applying. Check that only the expected resources will be created.
After applying, verify your resources are running correctly:
- Set up monitoring from day one.
Common operational issues
Terraform state conflicts can occur with WAFv2 resources.
Error: Error deleting WAFv2 IPSet: WAFOptimisticLockException: AWS WAF couldn’t save your changes because someone changed the resource after you started to edit it. Re-apply your changes.
Resolution: Delete the IPsets manually and retry the terraform destroy command.
Rate limiting, IP blocking, and SQL injection prevention can be implemented with production-ready Terraform code you can adapt for your own infrastructure.
This downloads the AWS provider plugin and initializes the backend.
Conclusion
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 Security Automations for AWS WAF solution deployed via Terraform bridges the gap between security operations and infrastructure as code. Terraform automatically applies changes in the cloud and deploys and configures the AWS WAF settings and protective features across accounts and regions. The pattern creates IAM roles and Lambda functions, WAF ACL rules and IP sets, S3 buckets, EventBridge rules, Glue tables and Athena workgroups, and API Gateway resources from a single variable file.
Operational maturity comes from modular environments, strict naming conventions, avoidance of hardcoding, and separate S3 storage for static assets. Logging to aws-waf-logs- prefixed CloudWatch log groups with 90 day retention, filtered to KEEP BLOCK and COUNT actions, provides actionable security analysis without excessive volume.
For related security topics, see how to implement DDoS protection with Terraform and how to implement security groups best practices with Terraform.