新手咨询:AWS Lambda调用WAF规则API的端点及代码实现
No worries at all—we all start somewhere with AWS! Let's walk through your questions step by step.
Request Endpoint
The request body you shared matches the AWS WAF Classic CreateRule API (note: AWS now recommends using WAFv2 for new projects, but we’ll focus on the version matching your provided syntax first).
WAF Classic has two endpoint types based on your target resource:
- For CloudFront (global resources): Use the global endpoint
https://waf.amazonaws.com/ - For regional resources (like ALBs or API Gateways): Use a region-specific endpoint in the format
https://waf.<your-region>.amazonaws.com/(e.g.,https://waf.us-east-1.amazonaws.com/)
Important note: The ChangeToken in your request body isn’t a static string—you must first call the GetChangeToken API to retrieve a valid token, which prevents concurrent conflicts when modifying WAF configurations.
Lambda Code Example (Python)
Below is a complete, beginner-friendly Lambda function using Python’s boto3 library to call the WAF Classic CreateRule API.
Step 1: Configure IAM Permissions
First, make sure your Lambda execution role has these permissions (add them via an IAM policy):
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "waf:CreateRule", "waf:GetChangeToken" ], "Resource": "*" } ] }
Step 2: Lambda Function Code
import boto3 import logging # Set up basic logging logger = logging.getLogger() logger.setLevel(logging.INFO) def lambda_handler(event, context): # Initialize WAF client (add region_name if targeting regional resources, e.g., region_name='us-east-1') waf_client = boto3.client('waf') try: # 1. Fetch a valid ChangeToken token_response = waf_client.get_change_token() change_token = token_response['ChangeToken'] logger.info(f"Retrieved valid ChangeToken: {change_token}") # 2. Call CreateRule API rule_result = waf_client.create_rule( ChangeToken=change_token, MetricName='MyFirstWafRule_Metric', # Must be unique; use letters, numbers, and hyphens only Name='MyFirstWafRule' # Custom rule name # Optional: Add match conditions (e.g., IP blocks, SQL injection detection) here # Predicates=[ # { # 'DataId': 'your-ip-set-id', # 'Negated': False, # 'Type': 'IPMatch' # } # ] ) logger.info(f"Rule created successfully: {rule_result}") return { 'statusCode': 200, 'body': f"Rule created! Rule ID: {rule_result['Rule']['RuleId']}" } except Exception as e: logger.error(f"Error creating rule: {str(e)}") return { 'statusCode': 500, 'body': f"Failed to create rule: {str(e)}" }
Quick Tips
- If you need to add security conditions (like blocking specific IPs or detecting SQL injection), first create the required resources (e.g., IP sets) and reference their IDs in the
Predicatesparameter. - For new projects, consider using AWS WAFv2 instead—it has more features, and its endpoint follows the format
https://wafv2.<region>.amazonaws.com/with a slightly different request body structure.
内容的提问来源于stack exchange,提问作者Rudziankoŭ

