Home > Mobile >  terraform combine 2 objects with 2 attributes for aws instance_ids
terraform combine 2 objects with 2 attributes for aws instance_ids

Time:04-27

Following hashicorp doc to leverage for_each to provision multiple instance using local var map.

I am unable to get the instance_ids into a single lists for output:

output "instance_ids" {
  description = "IDs of EC2 instances"
  value       = { for p in sort(keys(var.project)) : p => module.ec2_instances[p].instance_ids }
}

This is the output:

instance_ids = {
  "client-webapp" = [
    "i-0e11fcc341e6ce292",
    "i-0b7ddd178c0590116",
    "i-0c570628d3997874b",
    "i-0a1642d7cc173f329",
  ]
  "internal-webapp" = [
    "i-0e65c8569f2d2c6f5",
    "i-0c62e911e9446c53b",
  ]
}

Looking to get both objects lists of instance_ids into single list. Any good recommendation? Attempt to use merge, flatten, concat fail with various errors.

The var context for ids in above output loops thru the KEYs 'client-webapp' & 'internal-webapp'

variable "project" {
  description = "Map of project names to configuration."
  type        = map
  default     = {
    client-webapp = {
      public_subnets_per_vpc  = 2,
      private_subnets_per_vpc = 2,
      instances_per_subnet    = 2,
      instance_type           = "t2.micro",
      environment             = "dev"
    },
    internal-webapp = {
      public_subnets_per_vpc  = 1,
      private_subnets_per_vpc = 1,
      instances_per_subnet    = 2,
      instance_type           = "t2.nano",
      environment             = "test"
    }
  }
}

Any suggestions?

CodePudding user response:

You can concatenate both lists together.

locals {
    instance_ids = {
    "client-webapp" = [
      "i-0e11fcc341e6ce292",
      "i-0b7ddd178c0590116",
      "i-0c570628d3997874b",
      "i-0a1642d7cc173f329",
    ]
    "internal-webapp" = [
      "i-0e65c8569f2d2c6f5",
      "i-0c62e911e9446c53b",
    ]
  }

  new-list = concat(local.instance_ids["client-webapp"], local.instance_ids["internal-webapp"])
}

output "new-list" {
  description = "my new list"
  value = local.new-list
}

Here is the output

Changes to Outputs:
    new-list = [
        "i-0e11fcc341e6ce292",
        "i-0b7ddd178c0590116",
        "i-0c570628d3997874b",
        "i-0a1642d7cc173f329",
        "i-0e65c8569f2d2c6f5",
        "i-0c62e911e9446c53b",
    ]

CodePudding user response:

Instead of creating a map with the p =>, can you just return the array? And flatten.

Something like...

output "instance_ids" {
  description = "IDs of EC2 instances"
  value       = flatten({ for p in sort(keys(var.project)) : module.ec2_instances[p].instance_ids })
}
  • Related