我正在将IaC部署到AWS。除了我通过ASG部署EC2实例时遇到的困惑,一切都很好。当我运行Terraform apply时,出现以下错误消息:
“安全组sg-xxxxx和子网subnet-xxxxx属于不同的网络。启动EC2实例失败。”
Terraform正在尝试使用默认子网,而不是我定义要与创建的vpc一起使用的子网。目前,我仅使用LC和ASG而不使用ELB。下面是代码片段。任何见识都会有所帮助!
/******************************************************************
Subnet Definitions
*******************************************************************/
//Define the public subnet for availability zone A.
resource "aws_subnet" "Subnet_A_Public" {
vpc_id = "${aws_vpc.terraform-vpc.id}"
cidr_block = "${var.public_subnet_a}"
availability_zone = "${var.availability_zone_a}"
tags {
Name = "Subnet A - Public"
}
}
//Define the public subnet for availability zone B.
resource "aws_subnet" "Subnet_B_Public" {
vpc_id = "${aws_vpc.terraform-vpc.id}"
cidr_block = "${var.public_subnet_b}"
availability_zone = "${var.availability_zone_b}"
tags {
Name = "Subnet B - Public"
}
}
/*********************************************************************
Security Group (SG) Definitions
**********************************************************************/
//Define the public security group.
resource "aws_security_group" "tf-public-sg" {
name = "TF-Public-SG"
description = "Allow incoming HTTP/HTTPS connections and SSH access from the Internet."
vpc_id = "${aws_vpc.terraform-vpc.id}"
//Accept tcp port 80 (HTTP) from the Internet.
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
//Accept tcp port 443 (HTTPS) from the Internet.
ingress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
//Accept tcp port 22 (SSH) from the Internet.
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
//Accept all ICMP inbound from the Internet.
ingress {
from_port = -1
to_port = -1
protocol = "icmp"
cidr_blocks = ["0.0.0.0/0"]
}
lifecycle {
create_before_destroy = true
}
tags {
Name = "Terraform Public SG"
}
}
/**************************************************************************
PUBLIC ASG & LC
***************************************************************************/
resource "aws_launch_configuration" "terraform-public-lc" {
image_id = "${var.ami}"
instance_type = "${var.instance_type}"
security_groups = ["${aws_security_group.tf-public-sg.id}"]
lifecycle {
create_before_destroy = true
}
}
resource "aws_autoscaling_group" "tf-public-asg" {
launch_configuration = "${aws_launch_configuration.terraform-public-lc.id}"
availability_zones = ["${var.availability_zone_a}", "${var.availability_zone_b}"]
name = "tf-public-asg"
min_size = "${var.asg_min_pubic}"
max_size = "${var.asg_max_public}"
desired_capacity = "${var.asg_desired_capacity_public}"
tags {
key = "Name"
value = "tf-public-asg"
//value = "${var.public_instance_name}-${count.index}"
propagate_at_launch = true
}
}
/************************************************************************
END PUBLIC ASG & LC
*************************************************************************/