Search code examples
amazon-web-servicesterraformterraform-provider-awsamazon-aurora

How to set arguments of a resource with for_each


I am trying to create resource aws_rds_cluster_parameter_group, which loads the parameters from a list. I am trying to do that with for_each, but doesn't seem to work. Is there a way to achieve this? Here's what I have so far:

variable "parameters"       { type = list }
resource "aws_rds_cluster_parameter_group" "db-aurora-postgresql-cluster-parameter-group" {
    ...
   parameter {
     for_each = { for par in var.parameters : par.name => par }
       name    = each.value.name
       value   = each.value.value
  }
}

My tfvars looks like this:

    parameters = [
      {
        name  = "timezone"
        value = "CET"
      },...

I get these errors:

    Error: each.value cannot be used in this context
    
      on resources.tf line 21, in resource "aws_rds_cluster_parameter_group" "db-aurora-postgresql-cluster-parameter-group":
      21:     name    = each.value.name
    
    A reference to "each.value" has been used in a context in which it is
    unavailable, such as when the configuration no longer contains the value in
    its "for_each" expression. Remove this reference to each.value in your
    configuration to work around this error.

I also tried with dynamic "parameter" { but also doesn't work:

  dynamic "parameter" {
    for_each  = var.parameters
    name      = parameter.value["name"]
    value     = parameter.value["value"]
  }
    Error: Unsupported argument
    
      on resources.tf line 21, in resource "aws_rds_cluster_parameter_group" "db-aurora-postgresql-cluster-parameter-group":
      21:     name    = each.value.name
    
    An argument named "name" is not expected here.

Solution

  • Based on the provided code, you need to use dynamic, but it seems you have been using it wrong:

    resource "aws_rds_cluster_parameter_group" "db-aurora-postgresql-cluster-parameter-group" {
    ...
      dynamic "parameter" {
        for_each = { for par in var.parameters : par.name => par }
        content {
          name  = parameter.value.name
          value = parameter.value.value
        }
      }
    }