好吧,我在创建vpc、sgs和rds-db和ec2实例时遇到了问题。错误表明我在不同的VPC中有一个DB实例和EC2安全组。但是,是吗?我在一个vpc中分配了sgs,但我仍然不明白为什么我会出现这个错误。有人能给我解释一下吗?
resource "aws_vpc" "mainvpc" {
cidr_block = "10.0.0.0/16"
tags = {
Name = "main"
}
}
#Subnets
resource "aws_subnet" "public-subnet-1" {
vpc_id = aws_vpc.mainvpc.id
cidr_block = "10.0.0.0/24"
map_public_ip_on_launch = true
availability_zone = "us-east-2a"
tags = {
Name = "Public Subnet 1"
}
}
resource "aws_subnet" "private-subnet-1" {
vpc_id = aws_vpc.mainvpc.id
cidr_block = "10.0.2.0/24"
map_public_ip_on_launch = false
availability_zone = "us-east-2b"
tags = {
Name = "Private Subnet 1"
}
}
这是我创建的一个sgs,并将其分配给vpc mainvpc
# Security Group
resource "aws_security_group" "wp" {
name = "WP-sg"
description = "Allow SSH and HTTP inbound traffic"
vpc_id = aws_vpc.mainvpc.id
ingress {
description = "SSH traffic"
protocol = "tcp"
self = true
from_port = 22
to_port = 22
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
description = "HTTP traffic"
protocol = "tcp"
self = true
from_port = 80
to_port = 80
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
description = "Ping"
protocol = "icmp"
self = true
from_port = -1
to_port = -1
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
tags = {
Name = "SG for WordPress"
}
}
resource "aws_security_group" "db" {
description = "Allow WordPress inbound traffic"
vpc_id = aws_vpc.mainvpc.id
ingress {
description = "Wordpress traffic"
protocol = "tcp"
self = true
from_port = 3306
to_port = 3306
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
depends_on = [aws_security_group.wp]
tags = {
Name = "SG for Mysql"
}
}
#DB
resource "aws_db_instance" "db" {
allocated_storage = 15
max_allocated_storage = 100
engine = "mysql"
engine_version = "5.7"
instance_class = "db.t2.micro"
name = "dbwp"
username = "---"
password = "---"
parameter_group_name = "default.mysql5.7"
skip_final_snapshot = true
vpc_security_group_ids = [aws_security_group.db.id]
}
# EC2
resource "aws_instance" "app_yi" {
ami = "---"
instance_type = "t2.micro"
vpc_security_group_ids = [aws_security_group.wp.id]
depends_on = [aws_db_instance.db]
}
错误表明我在不同的VPCs中有一个DB实例和EC2安全组。但是,是吗?
是的,数据库和EC2实例都在default
VPC中,而不是在您创建的mainvpc
中。
对于EC2实例,为了与您的安全组位于同一VPC中,您必须指定subnet_id
,或者必须创建一个需要subnet_id
的aws_network_interface
。
对于数据库,您必须创建一个aws_db_subnet_group
,并在aws_db_instance
资源上指定db_subnet_group_name
的子网组名称。