Home > Net >  Terraform cannot convert tuple to map of any single type
Terraform cannot convert tuple to map of any single type

Time:08-31

locals {
  ec2_instance = tomap([{
    a = "ami-08d4ac5b634553e16"
    b = "t2.medium"
    },
    {
      a = "ami-07638e60c0d01f44f"
      b = "t2.micro"
    },
    {
      a = "ami-0729e439b6769d6ab"
      b = "t2.small"
    }

  ])
}

resource "aws_instance" "instance" {
  for_each = {
    for index, i in local.ec2_instance :
    i.a => i
  }

  ami           = each.a
  instance_type = each.b

  tags = {
    "Name" = "Terraform-${each.a}"
  }
  key_name        = var.key_name
  security_groups = var.security_groups
}

I keep getting the error message Invalid value for "v" parameter: cannot convert tuple to map of any single type. I've tried troubleshooting it but no progress.

I've defined the resources I want to create and how I want to use locals

CodePudding user response:

You can't use tomap, as you have a list of maps. Your local just should be:

locals {
  ec2_instance = [{
    a = "ami-08d4ac5b634553e16"
    b = "t2.medium"
    },
    {
      a = "ami-07638e60c0d01f44f"
      b = "t2.micro"
    },
    {
      a = "ami-0729e439b6769d6ab"
      b = "t2.small"
    }

  ])
}

Also you need to use value to access a and b:


resource "aws_instance" "instance" {
  for_each = {
    for index, i in local.ec2_instance :
    i.a => i
  }

  ami           = each.value.a
  instance_type = each.value.b

  tags = {
    "Name" = "Terraform-${each.value.a}"
  }
  key_name        = var.key_name
  security_groups = var.security_groups
}
  • Related