I am trying a use case , where I need to create an Instance based on the existing Subnet ID, VPC ID provided as an variable. And A Volume also has to be created in the same availability_zone and attached to the Instance created in that availability zone. But, during Instance creation, I need to find out which availability_zone does the Selected Subnet falls under. Based on that I need to create the “Instance” as well as the “Volume”.
For this use case, i need a filter that can give “availability_zone” of a specific subnet_id. But, I am unable to find such an syntax in the AWS Provider of Terraform. Can any one help here?
My Current Sample code is as below:
terraform {
required_providers {
aws = {
source = “hashicorp/aws”
version = “3.63.0”
}
}
}
provider “aws” {
Configuration options
access_key = “{var.access_key}"
secret_key = "{var.secret_key}”
profile = “default”
region = “${var.region}”
}
data “aws_availability_zones” “available” {
state = “available”
filter {
name = “opt-in-status”
values = [“opt-in-not-required”]
}
}
resource “aws_instance” “default” {
availability_zone = data.aws_availability_zones.available.names[0]
ami = “{var.ami_id}"
instance_type = "{var.instance_type}”
key_name = “{var.key_pair}"
subnet_id = "{var.subnet_id}”
tags = {
Owner = “Siva”
Name = “${var.instance_name}”
}
}
resource “aws_security_group” “default” {
name = “{var.sgname}"
description = "Allow TLS inbound traffic"
vpc_id = "{var.vpc_id}”
tags = {
Owner = “Siva”
Name = “${var.instance_name}”
}
}
resource “aws_ebs_volume” “default” {
availability_zone = aws_instance.default.availability_zone
size = “{var.volume_size}"
type = "{var.volume_type}”
tags = {
Owner = “Siva”
Name = “${var.instance_name}”
}
}
resource “aws_volume_attachment” “default” {
device_name = “/dev/sdh”
volume_id = aws_ebs_volume.default.id
instance_id = aws_instance.default.id
}