'How to get subnet_id of ec2 instances in AWS using Terraform?

Suppose we have some ec2 instances in AWS. How can we get subnet_ids of these ec2s via Terraform?



Solution 1:[1]

You should use a data source to fetch the existing EC2 instance and then just reference the data source and the attribute subnet_id where needed. Check the documentation: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/instance#subnet_id

Solution 2:[2]

  1. Get the data related ec2 instances you want to get subnets of:
data "aws_instances" "ec2s" {
  filter {
    name   = "tag:Name"
    values = ["value"]
  }
}
  1. Get instance_id of each ec2 using count:
data "aws_instance" "ec2_subnets" {
  count    = length(data.aws_instances.ec2s.ids)
  instance_id = data.aws_instances.ec2s.ids[count.index]
}
  1. Now, subnets could be referred:
resource "aws_***" "***" {
  count           = length(data.aws_instance.ec2_subnets)
  subnet_id       = data.aws_instance.ec2_subnets[count.index].subnet_id
  ###
  # Other Terraform attributes
  ###
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Oscar Drai
Solution 2 Andromeda