Terraform - 在每个可用区创建 ec2 实例

Posted

技术标签:

【中文标题】Terraform - 在每个可用区创建 ec2 实例【英文标题】:Terraform - Create ec2 instances in each availability zone 【发布时间】:2021-12-09 22:49:56 【问题描述】:

我正在尝试使用此脚本创建多个 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 参数处理)并指定不同的子网 ID

有人可以帮忙吗。

【问题讨论】:

【参考方案1】:

有几种方法可以做到这一点。我建议创建一个具有 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"
  

【讨论】:

以上是关于Terraform - 在每个可用区创建 ec2 实例的主要内容,如果未能解决你的问题,请参考以下文章

Elastic Beanstalk:在同一可用区创建 EC2 和 RDS 实例

使用 EC2 可用区的最佳实践是啥?

EC2中的2个不同可用区是作为WAN还是LAN?

如何使用 terraform 在 LocalStack 上创建 EC2 实例?

如何在 Terraform 中创建 SSH 密钥?

新AMI发布时,Terraform重新创建EC2实例