Choolai Raj
Choolai Raj

Reputation: 131

getting output of multiple ec2 instances (tag name and Private ip) in Terraform

in my main.tf i am creating multiple ec2 instances with diff tags like this

 `resource "aws_instance" "AMZ-TRN01-V-APP" {`
  `ami                     = var.linux_ami[var.region]`
  `instance_type           = var.app_instance_type`
  `key_name                = var.linux_key_name`
  `vpc_security_group_ids  = [var.vpc_security_group_ids[var.region]]`
  `subnet_id               = var.subnetid`
  `count                   = var.app_count` 
  `tags = {`
  `Name        = "AMZ-TRN01-V-APP-${format("%02d", count.index + 1)}"`
  `Environment = var.env_tag`
  `}`
  `} `
 `resource "aws_instance" "AMZ-TRN01-V-DB" {`
 `ami                     = var.linux_ami[var.region]`
 `instance_type           = var.db.instance_type`
 `key_name                = var.linux_key_name`
 `vpc_security_group_ids  = [var.vpc_security_group_ids[var.region]]`
 `subnet_id               = var.subnetid`
 `count                   = var.db_count `
 `tags = {`
 `Name        = "AMZ-TRN01-V-DB-${format("%02d", count.index + 1)}"`
 `Environment = var.env_tag`
 ` }`
 `}`

in my outputs.tf i have

`output "tags" {`
`description = "List of tags of instances"`
`value       = aws_instance.AMZ-TRN01-V-APP.*.tags.Name`
`}`
`output "private_ip" {`
`description = "List of private IP addresses assigned to the instances"`
`value       = aws_instance.AMZ-TRN01-V-APP.*.private_ip`
`}`

How do i get the tag and private ip for AMZ-TRN01-V-DB servers in the same output?

Thanks

Upvotes: 0

Views: 6883

Answers (1)

Salim
Salim

Reputation: 418

You can combine the output from AMZ-TRN01-V-APP and AMZ-TRN01-V-DB into a list as follows for the ip addresses:

output "private_ips" {
description = "List of private IP addresses assigned to the DB and APP instances"
value       = [aws_instance.AMZ-TRN01-V-APP.*.private_ip,
               aws_instance.AMZ-TRN01-V-DB.*.private_ip]
}

The same applies for the tags:

output "tags" {
description = "List of tags of the APP and DB instances"
value       = [aws_instance.AMZ-TRN01-V-APP.*.tags.Name,
               aws_instance.AMZ-TRN01-V-DB.*.tags.Name]
}

Upvotes: 4

Related Questions