{Terraform} for ExpressionでLoop

参考文献: Terraform Up & Running (Yevgeniy Brikman著)
https://itnext.io/terraform-count-for-each-and-for-loops-1018526c2047

 

cat <<-'EOF' > variables.tf
variable "list01" {
  description = "list01"
  type = list(string)
  default = [ "user01", "user12345" ]
}


variable "map01" {
  description = "map01"
  type = map(string)
  default = {
    key1 = "val1"
    key2 = "val2"
  }
}

variable "buckets" {
  type        = list(object({
      name = string
      force_destroy = bool
      tags = map(string)
  }))

  default = [
    {
      name  = "001"
      force_destroy = true
      tags  =         {
          "key1" = "val001_1"
          "key2" = "val001_2"
        }
    },
    {
      name  = "002",
      force_destroy = false
      tags  =         {
          "key1" = "val002_1"
          "key2" = "val002_2"
        }
    }
  ]
}

EOF

cat <<-'EOF' > main.tf
provider "aws" {
  region = "ap-northeast-1"
}

resource "aws_s3_bucket" "bucket20231101" {
  for_each  = { for v in var.buckets : v.name => v }

  bucket   = "bucket20231101-${each.key}"
  force_destroy = each.value.force_destroy
  tags = { for key,value in each.value.tags : key => value }
}
EOF

cat <<-'EOF' > outputs.tf

output "list11" {
  value = [ for item in var.list01 : item ]
}

output "list12" {
  value = [ for item in var.list01 : item if length(item) > 7 ]
}

output "list2map" {
  value = { for index, item  in var.list01 : index => item }
}

output "map2list" {
  value = [ for key , val in var.map01 : "key is ${key} and val is ${val}" ]
}

output "map2map" {
  value = { for key , val in var.map01 : val => key }
}
EOF

terraform init
terraform fmt
terraform apply -auto-approve

terraform destroy -auto-approve