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

问题描述 投票:0回答:2

我正在尝试使用此脚本创建多个 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

有人可以帮忙吗。

amazon-ec2 terraform
2个回答
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}"
  }
}

0
投票
provider "aws" {
  alias = "ca-central-1"
  region = "ca-central-1"
  profile = var.aws_profile
}

provider "aws" {
   alias = "other-ca-central-1"
   region = "ca-central-1"
   profile = var.aws_other_profile
}
© www.soinside.com 2019 - 2024. All rights reserved.