1
votes

I have a module to create databases in AWS:

resource "aws_rds_cluster_instance" "db_instances" {
  count      = lookup(var.argument, "count")
  identifier = lookup(var.argument, "identifier", count.index)
}

The argument variable is as follows:

variable "argument" {
  type = map(string)
}

In my root main.tf when I try to create 2 db instances I get an error as they're both trying to use the same identifier name, however since I used count.index in the module I thought it would take care of adding a number at the end of the db name.

variable "argument" {
  default = {
    count      = 2
    identifier = "my-db-name"
  }
}

How do I make my db names become "my-db-name-0" and "my-db-name-1"?

2

2 Answers

3
votes

From the looks of it you already using terraform 0.12...
I would recommend you using a for_each that way you can have more properties on your RDS variable, below is an example

variable "rds" {
  default = {
    "my-db-name-0" = {
      engine         = "foo"
      instance_class = "db.r4.large"
    }
    "my-db-name-1" = {
      engine         = "bar"
      instance_class = "db.r4.small"
    }
}

resource "aws_rds_cluster_instance" "db_instance" {
  for_each = var.rds

  identifier     = each.key
  engine         = each.value.engine
  instance_class = each.value.instance_class
}

This way the identifier names can be anything you want...
and it gives you the flexibility to customize each instance arguments:
https://www.terraform.io/docs/providers/aws/r/rds_cluster_instance.html#argument-reference

2
votes

You would do this through the use of the join function combined with the count.index value.

resource "aws_rds_cluster_instance" "db_instances" {
  count      = lookup(var.argument, "count")
  cluster_identifier = join("-", [lookup(var.argument, "identifier"), count.index])
  instance_class = "db.t2.small"
}