WAF & Shield Basics
Five short examples that create a Web ACL, add an AWS Managed Rule Group, attach it to an Application Load Balancer, and confirm it is working.
Busque em todas as páginas da documentação
Five short examples that create a Web ACL, add an AWS Managed Rule Group, attach it to an Application Load Balancer, and confirm it is working.
Each example shows the same operation in both Python (boto3) and TypeScript (AWS SDK for JavaScript v3). Run them in order; later steps reuse ids from earlier ones.
pip install boto3 (boto3 1.43.x, Python 3.10+). TypeScript: npm install @aws-sdk/client-wafv2 (Node.js 18+).aws configure, environment variables, or an IAM role with wafv2:CreateWebACL, wafv2:GetWebACL, wafv2:AssociateWebACL, and wafv2:GetSampledRequests.CreateWebACL builds the ACL container. DefaultAction decides what happens to requests that match no rule.
# --- Python (boto3) ---
import boto3
wafv2 = boto3.client("wafv2", region_name="us-east-1")
resp = wafv2.create_web_acl(
Name="demo-web-acl",
Scope="REGIONAL",
DefaultAction={"Allow": {}},
VisibilityConfig={
"SampledRequestsEnabled": True,
"CloudWatchMetricsEnabled": True,
"MetricName": "demoWebAcl",
},
Rules=[],
)
web_acl_id = resp["Summary"]["Id"]
web_acl_arn = resp["Summary"]["ARN"]// --- TypeScript (AWS SDK v3) ---
import { WAFV2Client, CreateWebACLCommand } from "@aws-sdk/client-wafv2";
const wafv2 = new WAFV2Client({ region: "us-east-1" });
const resp = await wafv2.send(new CreateWebACLCommand({
Name: "demo-web-acl",
Scope: "REGIONAL",
DefaultAction: { Allow: {} },
VisibilityConfig: {
SampledRequestsEnabled: true,
CloudWatchMetricsEnabled: true,
MetricName: "demoWebAcl",
},
Rules: [],
}));
const webAclId = resp.Summary?.Id;
const webAclArn = resp.Summary?.ARN;Scope: "REGIONAL" is for an ALB, API Gateway, AppSync API, or Cognito pool; use CLOUDFRONT (created against us-east-1) for a CloudFront distribution.VisibilityConfig is required on the ACL and on every rule - it drives both CloudWatch metrics and sampled-request visibility.Rules array is valid; you add rules next rather than inline here for clarity.AssociateWebACL.Reference a managed rule group by name instead of writing individual match rules. UpdateWebACL requires the current LockToken from GetWebACL.
# --- Python (boto3) ---
current = wafv2.get_web_acl(Name="demo-web-acl", Scope="REGIONAL", Id=web_acl_id)
lock_token = current["LockToken"]
wafv2.update_web_acl(
Name="demo-web-acl",
Scope="REGIONAL",
Id=web_acl_id,
DefaultAction={"Allow": {}},
LockToken=lock_token,
VisibilityConfig={
"SampledRequestsEnabled": True,
"CloudWatchMetricsEnabled": True,
"MetricName": "demoWebAcl",
},
Rules=[{
"Name": "AWS-CommonRuleSet",
"Priority": 0,
"OverrideAction": {"None": {}},
"Statement": {
"ManagedRuleGroupStatement": {
"VendorName": "AWS",
"Name": "AWSManagedRulesCommonRuleSet",
}
},
"VisibilityConfig": {
"SampledRequestsEnabled": True,
"CloudWatchMetricsEnabled": True,
"MetricName": "commonRuleSet",
},
}],
)// --- TypeScript (AWS SDK v3) ---
import { GetWebACLCommand, UpdateWebACLCommand } from "@aws-sdk/client-wafv2";
const current = await wafv2.send(new GetWebACLCommand({
Name: "demo-web-acl", Scope: "REGIONAL", Id: webAclId,
}));
const lockToken = current.LockToken;
await wafv2.send(new UpdateWebACLCommand({
Name: "demo-web-acl",
Scope: "REGIONAL",
Id: webAclId,
DefaultAction: { Allow: {} },
LockToken: lockToken,
VisibilityConfig: {
SampledRequestsEnabled: true,
CloudWatchMetricsEnabled: true,
MetricName: "demoWebAcl",
},
Rules: [{
Name: "AWS-CommonRuleSet",
Priority: 0,
OverrideAction: { None: {} },
Statement: {
ManagedRuleGroupStatement: {
VendorName: "AWS",
Name: "AWSManagedRulesCommonRuleSet",
},
},
VisibilityConfig: {
SampledRequestsEnabled: true,
CloudWatchMetricsEnabled: true,
MetricName: "commonRuleSet",
},
}],
}));WAFV2 uses optimistic locking - every UpdateWebACL call needs the LockToken from the most recent GetWebACL, or it fails.AWSManagedRulesCommonRuleSet covers broad, generic threats (bad inputs, common exploits); it is a reasonable first managed group for most apps.OverrideAction: {"None": {}} means the managed group's own rule actions (mostly block) apply as authored; Count would only log matches instead of blocking.Priority must be unique per rule and determines evaluation order, lowest first.Nothing is protected until AssociateWebACL links the ACL's ARN to a resource ARN.
# --- Python (boto3) ---
alb_arn = "arn:aws:elasticloadbalancing:us-east-1:111111111111:loadbalancer/app/demo-alb/abc123"
wafv2.associate_web_acl(WebACLArn=web_acl_arn, ResourceArn=alb_arn)// --- TypeScript (AWS SDK v3) ---
import { AssociateWebACLCommand } from "@aws-sdk/client-wafv2";
const albArn = "arn:aws:elasticloadbalancing:us-east-1:111111111111:loadbalancer/app/demo-alb/abc123";
await wafv2.send(new AssociateWebACLCommand({ WebACLArn: webAclArn, ResourceArn: albArn }));WebACLId field instead of a separate AssociateWebACL call.REGIONAL-scope ACL can only associate with resources in its own region.GetWebACLForResource confirms which Web ACL, if any, protects a given resource.
# --- Python (boto3) ---
resp = wafv2.get_web_acl_for_resource(ResourceArn=alb_arn)
print(resp.get("WebACL", {}).get("Name"))// --- TypeScript (AWS SDK v3) ---
import { GetWebACLForResourceCommand } from "@aws-sdk/client-wafv2";
const resp = await wafv2.send(new GetWebACLForResourceCommand({ ResourceArn: albArn }));
console.log(resp.WebACL?.Name);WebACL key) means the resource has no Web ACL attached.ListResourcesForWebACL to go the other direction - given an ACL, list everything it protects.GetSampledRequests pulls a recent sample of matched traffic without setting up any logging pipeline.
# --- Python (boto3) ---
from datetime import datetime, timedelta, timezone
now = datetime.now(timezone.utc)
resp = wafv2.get_sampled_requests(
WebAclArn=web_acl_arn,
RuleMetricName="commonRuleSet",
Scope="REGIONAL",
TimeWindow={"StartTime": now - timedelta(hours=1), "EndTime": now},
MaxItems=50,
)
for item in resp["SampledRequests"]:
print(item["Action"], item["Request"]["URI"])// --- TypeScript (AWS SDK v3) ---
import { GetSampledRequestsCommand } from "@aws-sdk/client-wafv2";
const now = new Date();
const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000);
const resp = await wafv2.send(new GetSampledRequestsCommand({
WebAclArn: webAclArn,
RuleMetricName: "commonRuleSet",
Scope: "REGIONAL",
TimeWindow: { StartTime: oneHourAgo, EndTime: now },
MaxItems: 50,
}));
for (const item of resp.SampledRequests ?? []) {
console.log(item.Action, item.Request?.URI);
}RuleMetricName scopes the sample to one rule's VisibilityConfig.MetricName, not the whole ACL.PutLoggingConfiguration instead, covered on a later page.MaxItems caps at 500 per call; sampling is not exhaustive, just representative.Related: Web ACLs, Rules & Rule Groups - combining managed groups with custom rules.
Stack versions: This page was written for boto3 1.43.x (Python 3.10+) and the AWS SDK for JavaScript v3 (Node.js 18+).
Revisado por Chris St. John·Última atualização: 25 de jul. de 2026