Home > Software engineering >  Terraform how to output object id that were created using count
Terraform how to output object id that were created using count

Time:04-13

I have a terraform module that creates 2 subnets. I need somehow to get the output for each subnet. When using the [count.index] as part of the output block I'm getting an error that count can not be used.

So what should be the solution since I need to associate ec2 to a specific subnet.

module "private_subnet" {
     source = "./modules/private_subnet"
     vpc_id = module.vpc.vpcid
     number_of_subnets = 2
     private-subnet-block = var.private-subnet-block
     tag_enviroment= var.tag_enviroment
     project_name = var.project_name }



 resource "aws_subnet" "private_subnet" {
        count = var.number_of_subnets
        cidr_block = var.private-subnet-block[count.index]
        availability_zone = var.availability_zone[count.index]
        vpc_id = var.vpc_id   
        map_public_ip_on_launch = false
        tags = {
        Name = "${var.project_name}-private-subnet-${count.index 1}"
        env = var.tag_enviroment   } }

output "privatesubnetid"{
    value = aws_subnet.private_subnet[count.index].id }

Error message :

Error: Reference to "count" in non-counted context │ │ on modules/private_subnet/output.tf line 2, in output "privatesubnetid": │ 2: value = aws_subnet.private_subnet[count.index].id │ │ The "count" object can only be used in "module", "resource", and "data" blocks, and only when the "count" argument is set

CodePudding user response:

This can help you:

output "database_subnets" {
  description = "IDs of database subnets"
  value       = aws_subnet.database.*.id
}

output "database_subnet_group" {
  description = "ID of database subnet group"
  value       = concat(aws_db_subnet_group.database.*.id, [""])[0]
}

CodePudding user response:

You can use Terraform splat expression [1]:

output "privatesubnetid" {
    value = aws_subnet.private_subnet[*].id 
}

[1] https://www.terraform.io/language/expressions/splat

  • Related