Terraformを使用してAWS WAFのログ出力をCloudWatch Logsに設定する際、適切にCloudWatch Log Groupを指定する方法について説明します。
AWS WAFのログ出力設定において、CloudWatch Log Groupを直接指定することは、一般的なアプローチです。以下に、AWS WAFのログをCloudWatch Log Groupに出力するための完全なTerraformコード例を示します。
1. プロバイダ設定と変数
まず、AWSプロバイダと必要な変数を設定します。
provider "aws" {
region = "us-west-2" # 必要に応じて変更
}
variable "log_group_name" {
description = "The name of the CloudWatch Log Group"
default = "waf-logs"
}
variable "web_acl_name" {
description = "The name of the WAF Web ACL"
default = "example-web-acl"
}
2. CloudWatch Log Groupの作成
次に、CloudWatch Log Groupを作成します。
resource "aws_cloudwatch_log_group" "waf_log_group" {
name = var.log_group_name
}
3. WAF Web ACLの作成
WAFのWeb ACLを作成します。
resource "aws_wafv2_web_acl" "example" {
name = var.web_acl_name
description = "An example WAF"
scope = "REGIONAL" # CloudFrontの場合は "CLOUDFRONT" を使用
default_action {
allow {}
}
visibility_config {
cloudwatch_metrics_enabled = true
metric_name = "waf-example"
sampled_requests_enabled = true
}
rule {
name = "rule-1"
priority = 1
action {
allow {}
}
statement {
byte_match_statement {
field_to_match {
method {}
}
positional_constraint = "CONTAINS"
search_string = "POST"
text_transformation = "NONE"
}
}
visibility_config {
cloudwatch_metrics_enabled = true
metric_name = "example-rule-1"
sampled_requests_enabled = true
}
}
}
4. Logging Configurationの作成
WAF Web ACLに対してログ出力設定を行います。この際、CloudWatch Log Groupを指定します。
resource "aws_wafv2_logging_configuration" "example" {
log_destination_configs = [aws_cloudwatch_log_group.waf_log_group.arn]
resource_arn = aws_wafv2_web_acl.example.arn
}
全体の構成例
provider "aws" {
region = "us-west-2" # 必要に応じて変更
}
variable "log_group_name" {
description = "The name of the CloudWatch Log Group"
default = "waf-logs"
}
variable "web_acl_name" {
description = "The name of the WAF Web ACL"
default = "example-web-acl"
}
resource "aws_cloudwatch_log_group" "waf_log_group" {
name = var.log_group_name
}
resource "aws_wafv2_web_acl" "example" {
name = var.web_acl_name
description = "An example WAF"
scope = "REGIONAL" # CloudFrontの場合は "CLOUDFRONT" を使用
default_action {
allow {}
}
visibility_config {
cloudwatch_metrics_enabled = true
metric_name = "waf-example"
sampled_requests_enabled = true
}
rule {
name = "rule-1"
priority = 1
action {
allow {}
}
statement {
byte_match_statement {
field_to_match {
method {}
}
positional_constraint = "CONTAINS"
search_string = "POST"
text_transformation = "NONE"
}
}
visibility_config {
cloudwatch_metrics_enabled = true
metric_name = "example-rule-1"
sampled_requests_enabled = true
}
}
}
resource "aws_wafv2_logging_configuration" "example" {
log_destination_configs = [aws_cloudwatch_log_group.waf_log_group.arn]
resource_arn = aws_wafv2_web_acl.example.arn
}
この設定により、AWS WAFのログが指定されたCloudWatch Log Groupに出力されるようになります。Terraformの状態管理や計画確認 (terraform plan) を行い、問題がないことを確認した上で terraform apply を実行してください。

コメント