Here below i am attaching my full code , specifically in target for loop section facing the issue . someone help us on this . Also Attaching error message at the end for debugging
provider “aws” {
region = var.region
}
VPC Module
module “vpc” {
source = “terraform-aws-modules/vpc/aws”
version = “5.17.0”
name = “vpc”
cidr = “10.0.0.0/16”
azs = [“us-east-1a”]
public_subnets = [“10.0.1.0/24”]
enable_nat_gateway = false
tags = {
Name = “vpc”
}
}
Security Group Module
module “security_group” {
source = “terraform-aws-modules/security-group/aws”
version = “5.2.0”
name = “instance-sg”
vpc_id = module.vpc.vpc_id
ingress_with_cidr_blocks = [
{
from_port = 22
to_port = 22
protocol = “tcp”
cidr_blocks = “0.0.0.0/0” # Changed to list
description = “Allow SSH”
},
{
from_port = 80
to_port = 80
protocol = “tcp”
cidr_blocks = “0.0.0.0/0” # Changed to list
description = “Allow HTTP”
}
]
egress_with_cidr_blocks = [
{
from_port = 0
to_port = 0
protocol = “-1”
cidr_blocks = “0.0.0.0/0” # Changed to list
description = “Allow all outbound traffic”
}
]
tags = {
Name = “instance-security-group”
}
}
EC2 Instances
resource “aws_instance” “demo” {
count = 2 # Create 2 instances
ami = var.ami
instance_type = var.instance_type
subnet_id = module.vpc.public_subnets[0] # Ensure single subnet is selected
key_name = “terraform_key”
security_groups = [module.security_group.security_group_id] # Fixed attribute
root_block_device {
volume_size = 20 # Storage in GB
volume_type = “gp2”
}
tags = {
Name = “my-instance-${count.index}” # Unique names for instances
}
}
Load Balancer Module
module “load_balancer” {
source = “terraform-aws-modules/alb/aws”
version = “9.13.0”
name = “app-load-balancer”
load_balancer_type = “application”
security_groups = [module.security_group.security_group_id]
subnets = module.vpc.public_subnets
target_groups = [
{
name = “app-target-group”
port = 80
protocol = “HTTP”
vpc_id = module.vpc.vpc_id
targets = [
for i in range(length(aws_instance.demo)) : {
target_id = aws_instance.demo[i].id # Access the ID with index
port = 80
}
]
}
]
tags = {
Name = “app-load-balancer”
}
}
Error message :
│ Error: Unsupported attribute
│
│ on .terraform\modules\load_balancer\main.tf line 597, in resource “aws_lb_target_group_attachment” “this”:
│ 597: target_id = each.value.target_id
│ ├────────────────
│ │ each.value is object with 5 attributes
│
│ This object does not have an attribute named “target_id”.