Home > front end >  How I can get the AWS RDS writer instance in Terraform
How I can get the AWS RDS writer instance in Terraform

Time:11-21

I am using terraform aws_rds_cluster and aws_rds_cluster_instances modules to provision the AWS RDS cluster (mysql). This creates the cluster with one writer and two read replicas. In the output.tf, I need to get the endpoint of the RDS writer instance.

output "rds_writer_instance_endpoint {
  value = aws_rds_cluster.instances.*.endpoint
}

I got all the endpoints for the three instances "aws_rds_cluster.instances.*.endpoint". How to retrieve only the writer endpoint?

CodePudding user response:

your instance objects will be returning with an attribute of writer. https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/rds_cluster_instance#attributes-reference

writer – Boolean indicating if this instance is writable. False indicates this instance is a read replica.

You can use this attribute to filter your list and return only objects that have this value set to true. Assuming that only one instance can be the writter I then use the one function of terraform to set the output as the value of the list.

output "rds_writer_instance_endpoint {
  value = one([for instance in aws_rds_cluster.instances]: var.endpoint if var.writer]) 
}

As an example of this in action, I have created a list of variables that represent like your instances resource and apply the above pattern to it.

variable "instances" {
  type    = list(object({
    endpoint = string
    writer   = bool
  }))
  default = [
    {
      endpoint = "http:localhost:8080"
      writer    = false
    },
    {
      endpoint = "http:localhost:8081"
      writer    = true
    },
    {
      endpoint = "http:localhost:8082"
      writer    = false
    }
  ]
}

output "all_out" {
  value = var.instances.*.endpoint
}

output "writer" {
  value = one([for instance in var.instances: instance.endpoint if instance.writer])
}

OUTPUT

Outputs:

all_out = tolist([
  "http:localhost:8080",
  "http:localhost:8081",
  "http:localhost:8082",
])
writer = "http:localhost:8081"

  • Related