我正在尝试使用Terrafom部署EC2实例,我可以看到以下错误:
Error: Error launching source instance: InvalidGroup.NotFound: The security group 'prod-web-servers-sg' does not exist in VPC 'vpc-db3a3cb3'
这是我正在使用的Terraform模板:
resource "aws_default_vpc" "default" {
}
resource "aws_security_group" "prod-web-servers-sg" {
name = "prod-web-servers-sg"
description = "security group for production grade web servers"
vpc_id = "${aws_default_vpc.default.id}"
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
#Subnet
resource "aws_subnet" "private_subnet" {
vpc_id = "${aws_default_vpc.default.id}"
cidr_block = "172.31.0.0/24"
availability_zone = "ap-south-1a"
}
resource "aws_instance" "prod-web-server" {
ami = "ami-04b1ddd35fd71475a"
count = 2
key_name = "test_key"
instance_type = "r5.large"
security_groups = ["prod-web-servers-sg"]
subnet_id = "${aws_subnet.private_subnet.id}"
}
您有一个竞争条件,因为Terraform不知道要等到创建了安全组后才能创建实例。
要解决此问题,您应该将aws_security_group.prod-web-servers-sg.id
插入到aws_instance.prod-web-server
资源中,这样它就可以计算出资源之间的依赖链。您还应该使用vpc_security_group_ids
,而不是aws_instance
资源文档中提到的security_groups
:
security_groups-(可选,仅限EC2 Classic和默认VPC(要关联的安全组名称(EC2 Classic(或ID(默认VPC。
注意:如果您在VPC中创建实例,请使用VPC_security_group_ids。
所以你应该有这样的东西:
resource "aws_default_vpc" "default" {}
resource "aws_security_group" "prod-web-servers-sg" {
name = "prod-web-servers-sg"
description = "security group for production grade web servers"
vpc_id = aws_default_vpc.default.id
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
#Subnet
resource "aws_subnet" "private_subnet" {
vpc_id = aws_default_vpc.default.id
cidr_block = "172.31.0.0/24"
availability_zone = "ap-south-1a"
}
resource "aws_instance" "prod-web-server" {
ami = "ami-04b1ddd35fd71475a"
count = 2
key_name = "test_key"
instance_type = "r5.large"
vpc_security_group_ids = [aws_security_group.prod-web-servers-sg.id]
subnet_id = aws_subnet.private_subnet.id
}