Terraform:如何仅在支持请求的实例类型的区域中请求AWS EC2实例?

时间:2020-09-19 13:08:36

标签: amazon-web-services amazon-ec2 terraform terraform-provider-aws

在请求实例之前,是否有办法获取可用实例类型(例如t3.medium)可用的可用区?我正在尝试运行following code,对于某些区域,它会失败,并显示以下错误:

Error: Error launching source instance: Unsupported: Your requested instance type (t3.micro) is not supported in your requested Availability Zone (us-east-1e). Please retry your request by not specifying an Availability Zone or choosing us-east-1a, us-east-1b, us-east-1c, us-east-1d, us-east-1f.

很明显,我可以手动将可用区域指定为受支持的区域之一,但是我想最小化硬编码可用区域。

1 个答案:

答案 0 :(得分:4)

如评论中所述,如果您不愿意使用首选类型,而又愿意旋转其他类型的实例,则可以使用aws_ec2_instance_type_offering data source来回退到t2受影响的可用区中的实例族。

以下Terraform代码会将可用区映射输出到允许的实例类型,首选t3.micro但回退到t2.micro系列不可用的t3 s:< / p>

provider "aws" {
  region = "us-east-1"
}

data "aws_availability_zones" "all" {}

data "aws_ec2_instance_type_offering" "example" {
  for_each = toset(data.aws_availability_zones.all.names)

  filter {
    name   = "instance-type"
    values = ["t2.micro", "t3.micro"]
  }

  filter {
    name   = "location"
    values = [each.value]
  }

  location_type = "availability-zone"

  preferred_instance_types = ["t3.micro", "t2.micro"]
}

output "foo" {
  value = { for az, details in data.aws_ec2_instance_type_offering.example : az => details.instance_type }
}

这将输出:

foo = {
  "us-east-1a" = "t3.micro"
  "us-east-1b" = "t3.micro"
  "us-east-1c" = "t3.micro"
  "us-east-1d" = "t3.micro"
  "us-east-1e" = "t2.micro"
  "us-east-1f" = "t3.micro"
}

您不仅应该输出此信息,还应该能够遍历可用性区域以设置aws_instance资源的实例类型。

或者,您可以通过将输出更改为以下内容,对输出进行过滤以将其减少为仅可以提供t3实例族的可用区列表:

output "foo" {
  value = keys({ for az, details in data.aws_ec2_instance_type_offering.example : az => details.instance_type if details.instance_type == "t3.micro" })
}

这将输出以下内容,并跳过不包含t3实例族的可用性区域:

foo = [
  "us-east-1a",
  "us-east-1b",
  "us-east-1c",
  "us-east-1d",
  "us-east-1f",
]