skip to Main Content

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.

3

Answers


  1. Chosen as BEST ANSWER

    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
    }
    

  2. If you really want to use for_each with a variable of type number, then you can do an iterative type conversion with a for expression within a list constructor within a set type converter:

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

    But also it would fit naturally with the count meta-parameter as described in the answer posted by MarkoE simultaneous with this answer.

    Login or Signup to reply.
  3. Even though I feel information is lacking in the question, I think the better option here is to use the count meta-argument:

    resource "aws_db_instance" "replica_rds_instance" {
      count = var.rds_number_of_replicas //integer
      //something
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search