amazon-web-servicesamazon-ec2terraformterraform-provider-aws

Terraform launch EC2 condition based on count


Trying to launch 1 or 2 instances based on a condition ( "single-target" )

ERROR im getting :

132:   target_id        = var.ec2-2
var.ec2-2 is empty tuple
Inappropriate value for attribute "target_id": string required.

the use of that variable :

resource "aws_lb_target_group_attachment" "b" {
  target_id        = var.ec2-2

}

outputs :

output "ec2-2_ot" {
 value = aws_instance.ec2V2[*].id
 description = "the value of the network module ec2-2 id"
}

variable :

variable "single-target" {
  type=bool
  default=false
}

main.tf :

module "network_module" {
   ec2-2 = module.compute_module.ec2-2_ot
}

ec2 launch :

resource "aws_instance" "ec2V2" {
  count = var.single-target ? 0 : 1
  ami                         = var.ec2_ami
  instance_type               = var.ec2_type
  associate_public_ip_address = true
  key_name = var.key_pair
  vpc_security_group_ids = [ var.vpc-sg ]
  subnet_id = var.subnet-2
  user_data = file("PATH/user-data.sh")
          
  tags = {
    Name = var.ec2-2_name
  }
}

Solution

  • As the count has been already set to the resource you are trying to create, the returning result list would need to be accessed via Splat Expression mentioned in this terraform documentation.

    If you need to choose specific index from the list of the result , then you can use the element function to do so

    So in your case, if you need to output EC2 id it would be as follows.

    output "thisisoutput" {
           value = aws_instance.ec2V2[*].arn
    }