LoginSignup
7
2

More than 3 years have passed since last update.

terraformでAWS WAFを利用してCloudFrontのELBオリジンへ直接アクセスを制限

Posted at

こちらの記事のterraform版

# cloudfrontにカスタムヘッダーを付与して、ALBではそのヘッダーが付いていなければblockする

resource "aws_cloudfront_distribution" "cf" {
  ~略~
  origin {
    ~略~
    custom_header {
      name  = "${lookup(var.cf_custom_header_key, "${terraform.workspace}.value")}"
      value = "${lookup(var.cf_custom_header_value, "${terraform.workspace}.value")}"
    }
  }
}

resource "aws_wafregional_byte_match_set" "cloudfront_custom_header_match" {
  name = "cloudfront_custom_header_match"

  byte_match_tuples {
    text_transformation   = "NONE"
    target_string         = "${lookup(var.cf_custom_header_value, "${terraform.workspace}.value")}"
    positional_constraint = "CONTAINS"

    field_to_match {
      type = "HEADER"
      data = "${lookup(var.cf_custom_header_key, "${terraform.workspace}.value")}"
    }
  }
}

resource "aws_wafregional_rule" "block_ignore_cloudfront" {
  name        = "block-ignore-cloudfront"
  metric_name = "blockignorecloudfront"

  predicate {
    data_id = "${aws_wafregional_byte_match_set.cloudfront_custom_header_match.id}"
    negated = false
    type    = "ByteMatch"
  }
}

resource "aws_wafregional_web_acl" "block_ignore_cloudfront_alc" {
  name        = "block-ignore-cloudfront-alc"
  metric_name = "blockignorecloudfrontalc"

  default_action {
    type = "BLOCK"
  }

  rule {
    action {
      type = "ALLOW"
    }

    priority = 1
    rule_id  = "${aws_wafregional_rule.block_ignore_cloudfront.id}"
  }
}

resource "aws_wafregional_web_acl_association" "block_ignore_cloudfront_attach_alb" {
  resource_arn = "xxxxxxxxxxxxxxxxxxxx"
  web_acl_id   = "${aws_wafregional_web_acl.block_ignore_cloudfront_alc.id}"
}

7
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
2