Creating dynamic resources with Terraform for_each

Viewed 2609

I would like to create AWS SSM Parameters using Terraform, with the parameters being passed in as input variables.

I see there is a for_each feature, but how can this be applied to top level properties within a terraform resource? From the documentation, the use of for_each appears to be restricted to not work on top level properties of a resource, am I misunderstanding?

This is what I am trying to accomplish:

main.tf

resource "aws_ssm_parameter" "ssm_parameters" {
  for_each = var.params
  content {
      name = name.value
      type  = "String"
      overwrite = true
      value = paramValue.value

      tags = var.tags 
      lifecycle {
        ignore_changes = [
          tags,
          value
        ]
      }
  }  
}

variables.tf

variable "params" {
  default = [
    {
      name   = "albUrl"
      paramValue = "testa"
    },
    {
      name   = "rdsUrl1"
      paramValue = "testb"
    },
    {
      name   = "rdsUrl2"
      valparamValueue = "testc"
    },
  ]
}
1 Answers

You can use for each, but you need to modify its syntax and fix syntax in your var.params:

variable "params" {
  default = [
    {
      name   = "albUrl"
      paramValue = "testa"
    },
    {
      name   = "rdsUrl1"
      paramValue = "testb"
    },
    {
      name   = "rdsUrl2"
      paramValue = "testc"
    },
  ]
}

Then to use for each, and create 3 ssm parameters:

resource "aws_ssm_parameter" "ssm_parameters" {

  for_each = {for v in var.params: v.name => v.paramValue}
  
  type  = "String"

  name = each.key
  value = each.value
  
  overwrite = true
}

In the above you have to project your list(map) to a map as it is required for for_each.

Related