Conditionally merge a map of objects in Terraform
13:37 29 Jan 2026

I have a map of objects, and I want to filter the objects into a new map based on another variable. I think this should be fairly simple, but I get an error when using merge (which I assumed would be the way to do it). I have the following in my locals:

locals {
  all_endpoints = {
    read_write = {
      name                   = "read-write-endpoint"
      vpc_subnet_ids         = var.vpc_subnet_ids
      vpc_security_group_ids = var.vpc_security_group_ids
    },
    read_only = {
      name                   = "read-only-endpoint"
      vpc_subnet_ids         = var.vpc_subnet_ids
      vpc_security_group_ids = var.vpc_security_group_ids
      target_role            = "READ_ONLY"
    }
  }

  endpoints = merge(local.all_endpoints["read_write"], var.engine_family != "SQLSERVER" ? local.all_endpoints["read_only"] : {})

The idea is that the endpoints map will always contain the read_write endpoint, but the read_only endpoint is conditional on the engine_family being something other than 'SQLSERVER'. Running a plan gives the following error:

│ Error: Inconsistent conditional result types
│ 
│   on main.tf line 23, in locals:
│   23:  endpoints = merge(local.all_endpoints["read_write"], var.engine_family != "SQLSERVER" ? local.all_endpoints["read_only"] : {})
│     ├────────────────
│     │ local.all_endpoints["read_only"] is object with 4 attributes
│     │ var.engine_family is a string
│ 
│ The true and false result expressions must have consistent types. The 'true' value includes object attribute "name", which is absent in the 'false' value.

Is my ternary syntax just wrong? Also, while reading around, I've come across posts suggesting merge only performs a shallow merge, and as my objects have a different number of attributes in each, a deep merge. may be required.

I've tried many iterations, and can't remember them all, so I've just cut it back to basics and provided the above error. Any help would be appreciated.

Terraform version is 1.10.5

merge terraform maps