Terraform—在每个可用分区中创建ec2实例



我试图用这个脚本创建多个ec2实例

resource "aws_instance" "my-instance" {
count = 3
ami           = ...
instance_type = ...
key_name = ...
security_groups = ...
tags = {
Name = "my-instance - ${count.index + 1}"
}
}

创建3个实例。但是这三个都在同一个可用性区域。我希望在每个可用区域中创建一个实例,或者在我提供的每个可用区域中创建一个实例。我该怎么做呢?

我读到我可以使用

subnet_id = ...

选项指定应该在其中创建实例的可用性区域。但是我无法弄清楚如何通过实例创建循环(目前由count处理)参数),并指定不同的subnet_id

有人能帮帮忙吗?

有几种方法可以做到这一点。我建议创建一个具有3个子网的VPC,并在每个子网中放置一个实例:

# Specify the region in which we would want to deploy our stack
variable "region" {
default = "us-east-1"
}
# Specify 3 availability zones from the region
variable "availability_zones" {
default = ["us-east-1a", "us-east-1b", "us-east-1c"]
}
terraform {
required_providers {
aws = {
source  = "hashicorp/aws"
version = "~> 3.0"
}
}
}
# Configure the AWS Provider
provider "aws" {
region = var.region
}
# Create a VPC
resource "aws_vpc" "my_vpc" {
cidr_block = "10.0.0.0/16"
tags = {
Name = "my_vpc"
}
}
# Create a subnet in each availability zone in the VPC. Keep in mind that at this point these subnets are private without internet access. They would need other networking resources for making them accesible
resource "aws_subnet" "my_subnet" {
count             = length(var.availability_zones)
vpc_id            = aws_vpc.my_vpc.id
cidr_block        = cidrsubnet("10.0.0.0/16", 8, count.index)
availability_zone = var.availability_zones[count.index]
tags = {
Name = "my-subnet-${count.index}"
}
}
# Put an instance in each subnet
resource "aws_instance" "foo" {
count         = length(var.availability_zones)
ami           = ...
instance_type = "t2.micro"
subnet_id     = aws_subnet.my_subnet[count.index].id
tags = {
Name = "my-instance-${count.index}"
}
}

最新更新