Dynamically creating route53 records

I’m trying to dynamically create an aws_route53_record resource.

I need to look for the hosts IP Addresses first, and then pass it to the records attribute dinamically.

I’ve tried the following:

# prod = module.database.slave_db_private_ip_prod output example
output "slave_db_private_ip_prod" {
  value = [aws_instance.slave01[*].private_ip, aws_instance.slave02[*].private_ip, aws_instance.slave03[*].private_ip, aws_instance.slave04[*].private_ip]
}

database_read_host_ip = {
    dev = module.database.slave_db_private_ip_non_prod
    test = module.database.slave_db_private_ip_non_prod
    staging = module.database.slave_db_private_ip_non_prod
    prod = module.database.slave_db_private_ip_prod
  }

resource "aws_route53_record" "db_read_endpoint" {
  count = length(var.database_read_host_ip)
  zone_id = var.route53_private_zone_id
  name    = "db-read.${var.route_private_zone_name}"
  type    = "CNAME"
  ttl     = "60"
  set_identifier = "db-read-${terraform.workspace}"
  records = [lookup(var.database_read_host_ip, terraform.workspace)]

  weighted_routing_policy {
    weight = "${ceil(100 / length(var.database_read_host_ip))}"
  }
}

The error that I get is:

The given value is not suitable for child module variable "database_read_host_ip" defined at modules/database/variables.tf:173,1-33: element "staging": string required

Also, ideally, the weighted_routing_policy parameter would only consider valid endpoints for the given workspace.
For example; if I’m in the prod workspace, then the values for dev, test and staging would be blank, therefore, TF shouldn’t consider them.

Is there a way to achieve this in Terraform?

Thanks in advance!

what does your variables.tf look like ??

variables.tf:

variable "database_write_host" {
  type        = map(string)
  description = "Database Write Host endpoint"
  default = {
    dev     = ""
    test    = ""
    staging = ""
    prod    = ""
  }
}

variable "database_read_host" {
  type        = map(string)
  description = "Database Read Host endpoint"
  default = {
    dev     = ""
    test    = ""
    staging = ""
    prod    = ""
  }
}

variable "database_write_host_ip" {
  type        = map(string)
  description = "Database Write Host endpoint"
  default = {
    dev     = ""
    test    = ""
    staging = ""
    prod    = ""
  }
}

variable "database_read_host_ip" {
  type        = map(string)
  description = "Database Read Host endpoint"
  default = {
    dev     = ""
    test    = ""
    staging = ""
    prod    = ""
  }
}

But I pass the database_read_host_ip values to the branch like this (as shown above already):

database_read_host_ip = {
    dev = module.database.slave_db_private_ip_non_prod
    test = module.database.slave_db_private_ip_non_prod
    staging = module.database.slave_db_private_ip_non_prod
    prod = module.database.slave_db_private_ip_prod
  }