1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Terraformでmap内の未定義keyを判定する

Posted at

Terraformでmap内にある未定義のkeyをifで判定する方法。
Terraform v0.12系でしか動作しない。

サンプル

variable item {
  default = {
    id           = 1
    empty_column = "not_empty" # この行をコメントアウトしたりすると検証できる
  }
}

locals {
  empty = "empty"
  item = merge({
    "empty_column" : local.empty
  }, var.item)
}

output item {
  value = local.item
}
  • コメントアウトなし
Outputs:

item = {
  "empty_column" = "not_empty"
  "id" = 1
}
  • コメントアウトあり
Outputs:

item = {
  "empty_column" = "empty"
  "id" = 1
}

使い道

DynamoDBでカラムそのものが存在しないケースとか使える

resource "aws_dynamodb_table" "basic-dynamodb-table" {
  name           = "table_name"
  read_capacity  = 1
  write_capacity = 1
  hash_key       = "id"

  attribute {
    name = "id"
    type = "N"
  }
}

resource "aws_dynamodb_table_item" "main" {
  table_name = "table_name"
  hash_key   = "id"

  item = <<ITEM
{
  %{if local.item["empty_column"] != local.empty} # ここがポイント
    "empty_column": { "S": "${local.item["empty_column"]}"},
  %{endif}
  "id": { "N": "${local.item["id"]}" }
}
ITEM
}

他の方法について

indexは存在しないキーを指定した場合はエラーが返るので使えなかった
https://www.terraform.io/docs/configuration/functions/index.html

lookupでもできるかもかもしれない
https://www.terraform.io/docs/configuration/functions/lookup.html

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?