Is it possible to create an EC2 instance while reusing already existing VPC?
Running the following code yields Error launching source instance: VPCIdNotSpecified: No default VPC for this user. GroupName is only supported for EC2-Classic and default VPC. (status code: 400):
data "aws_security_groups" "my_tib_sg" {
tags = {
Name = "my-security-group"
}
}
resource "aws_instance" "nginx" {
ami = data.aws_ami.aws-linux.id
instance_type = "t2.micro"
key_name = var.key_name
vpc_security_group_ids = [data.aws_security_groups.my_tib_sg.id]
# more, irrelevant stuff...
}
FWIU from the error, the aws_instance block requires a reference to my VPC, which basically exists in my security group. Besides, I can't find a way to refer a VPC in an aws_instance block.
Updating code per answers:
I updated the code per answers below:
data "aws_security_groups" "my_tib_sg" {
tags = {
Name = "my-tib-sg"
}
}
data "aws_subnet" "my_subnet" {
tags = {
Name = "my-tib-subnet-1"
}
}
resource "aws_network_interface" "my_ani" {
subnet_id = data.aws_subnet.my_subnet.id
private_ips = ["10.0.0.10"]
tags = {
Name = "my-tib-ani"
by = "TF_TF"
}
}
resource "aws_instance" "nginx" {
ami = data.aws_ami.aws-linux.id
instance_type = "t2.micro"
key_name = var.key_name
vpc_security_group_ids = [data.aws_security_groups.my_tib_sg.id]
network_interface {
network_interface_id = aws_network_interface.my_ani.id
device_index = 0
}
connection {
type = "ssh"
host = self.public_ip
user = "ec2-user"
private_key = file(var.private_key_path)
}
provisioner "remote-exec" {
inline = [
"sudo yum install nginx -y",
"sudo service nginx start"
]
}
}
But the error changes to "network_interface": conflicts with vpc_security_group_ids.
(needless to mention: both my_subnet and my_tib_sg use same VPC)