1
0

More than 1 year has passed since last update.

[AWS][Terraform] WAF v2 のデフォルトアクションを variable で指定したい

Last updated at Posted at 2022-05-20

Terraform で AWS WAF を作成するとき default_action を variable で指定したいと思ったんですよ。

デフォルトアクションを指定するには default_action{} ブロックの中に allow {} または block {} って書くのね。
こんな感じかな?

variable acl_name           { }
variable acl_scope          { default = "REGIONAL" }
variable acl_default_action { default = "allow" }

resource aws_wafv2_web_acl waf {
    name  = var.acl_name
    scope = var.acl_scope

    default_action {
        var.acl_default_action == "allow" ? allow {} : block {}
    }

おふぅ、エラーになりますね...

│ Error: Argument or block definition required
│ 
│   on waf.tf line 10, in resource "aws_wafv2_web_acl" "acl":
│   10: var.acl_default_action == "allow" ? allow {} : block {}
│ 
│ An argument or block definition is required here. To set an argument, use the equals sign "=" to introduce the argument value.

ここには、ブロックを書きなさいとのお達しです。まぁ、ドキュメントにもそう書いてありますしね。

こういう時はダイナミックブロックローカル変数の出番です。
var.acl_default_actionallow だったらローカル変数 acl_allow に一つだけ要素をもった配列をセット、allow 以外だったらローカル変数 acl_block に一つだけ要素をもった配列をセットしておきます。
で、dynamic ブロックで配列の要素数分回すことで allow {} または block {} ブロックを default_action {} ブロックに入れ込むわけです。

ちょっと何言ってるかよくわからないすかね?ソース見たほうがわかりやすいかも。

variable acl_name           { }
variable acl_scope          { default = "REGIONAL" }
variable acl_default_action { default = "allow" }
locals {
    acl_allow = var.acl_default_action == "allow" ? [true] : []
    acl_block = var.acl_default_action != "allow" ? [true] : []
}

resource aws_wafv2_web_acl waf {
    name  = var.acl_name
    scope = var.acl_scope

    dynamic default_action {
      for_each = local.acl_allow
      content {
        allow {}
      }
    }
    dynamic default_action {
      for_each = local.acl_block
      content {
        block {}
       }
    }

ちょっとトリッキーですが、現状、この解しかないかなーと。

追記
WAF v1 の時は、こうやってかけたから、こんなトリッキーなことしなくても良かったんすけどね

variable acl_name           { }
variable acl_default_action { default = "ALLOW" }   # ALLOW or BLOCK

resource aws_waf_web_acl waf {
    name  = var.acl_name

    default_action {
        type = var.acl_default_action
    }
1
0
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
1
0