gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 05:54:14 29 4
gpt4 key购买 nike

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

关于amazon-ec2 - Terraform - 在每个可用区中创建 ec2 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69691331/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com