Search code examples
amazon-web-servicesterraformterraform-provider-aws

How can I use for_each with a integer in Terraform?


I have the following code in Terraform:

resource "aws_db_instance" "replica_rds_instance" {
  for_each = var.rds_number_of_replicas //integer
  //something
}

But I receive the following error:

The given "for_each" argument value is unsuitable: the "for_each" argument must be a map, or set of strings, and you have provided a value of type number.

The var must be a number. I also tried to use toset(range(var.rds_number_of_replicas)) but I found another error:

The given "for_each" argument value is unsuitable: "for_each" supports maps and sets of strings, but you have provided a set containing type number.


Solution

  • Based on Matthew`s post I used:

    resource "aws_db_instance" "replica_rds_instance" {
      for_each = toset([ for num in range(var.rds_number_of_replicas) : tostring(num) ])
      //something
    }