我正在将 IaC 部署到 AWS。一切都很好,除了我通过 ASG 部署 EC2 实例时遇到的一个令人困惑的问题。当我运行 Terraform apply 时,我收到以下错误消息:
“安全组 sg-xxxxx 和子网子网-xxxxx 属于不同的网络。启动 EC2 实例失败。”
Terraform 正在尝试使用默认子网,而不是我定义的要与我创建的 vpc 一起使用的子网。我目前不使用 ELB,只使用 LC 和 ASG。以下是代码片段。任何见解都会有所帮助!
/******************************************************************
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
*************************************************************************/