Search code examples
terraforminterpolationamazon-ecs

Terraform - How to modify map keys?


In Terraform 0.12.xx, is it possible to modify the keys in the map instead of their respective values? Let us assume that we have the following in the module definition:

locals {
    task_logging = [
    for k, v in var.task_logging_options : {
      name = trimprefix(k,"TASK_LOGGING_")
      value = v
    }
  ]
}

However, trimprefix here only applies on value.

Then down below I am creating a task definition for ECS service:

{...}
"logConfiguration": {
        "logDriver": "awsfirelens",
        "secretOptions": [],
        "options": ${jsonencode(local.task_logging_options)}
    },
{...}

And finally, in the module instantiation, I am passing task_logging_options as follows:

task_logging_options = {
    TASK_LOGGING_Name = "es"
    TASK_LOGGING_Host = "some.host"
  }

Where local function should strip the prefix TASK_LOGGING_ to build a JSON object for Fluentbit configuration.

End result should be an object, similar to snippet from terraform plan:

~ logConfiguration = {
                        logDriver     = "awsfirelens"
                      ~ options       = {
                          - Buffer_Size       = "False" -> null
                          - HTTP_Passwd       = "READACTED" -> null
                          - HTTP_User         = "READACTED" -> null
                          - Host              = "READACTEDd" -> null
                          - Index             = "READACTED" -> null
                          - Name              = "es" -> null
                          - Port              = "READACTED" -> null
                          + TASK_LOGGING_Host = "some.host"
                          + TASK_LOGGING_Name = "es"
                          - Tls               = "On" -> null
                          - Trace_Output      = "On" -> null
                        }
                        secretOptions = []
                    }
   

Solution

  • Not fully understand what do you want to achieve, but you can use trimprefix(k,"TASK_LOGGING_") as key as well.

    For example:

    
    locals { 
      task_logging2 = [
        for k, v in var.task_logging_options : {
            trimprefix(k,"TASK_LOGGING_") = v
          }
        ]  
    }
    

    will result in local.task_logging2 being:

    [
      {
        "Host" = "some.host"
      },
      {
        "Name" = "es"
      },
    ]
    

    Update

    If object is required, the following could be used:

    locals {
      
      task_logging2 = {
        for k, v in var.task_logging_options : 
            trimprefix(k,"TASK_LOGGING_") => v
          }   
    }
    

    which results in local.task_logging2 being:

    {
      "Host" = "some.host"
      "Name" = "es"
    }