问题
Is there a way to get the availability zones where an instance type (e.g. t3.medium) is available before requesting the instance? I'm trying to run the following code and for certain regions it fails with the following error:
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.
Obviously I can manually specify the availability zone to one of the supported, but I want to minimize hardcoding availability zones.
回答1:
As mentioned in the comments, if you're happy to spin up a different type of instance if the preferred type isn't available then you can use the aws_ec2_instance_type_offering data source to instead fallback to the t2
instance family in the affected availability zone.
The following Terraform code will output a map of availability zones to the instance type allowed, preferring t3.micro
but falling back to t2.micro
s where the t3
family isn't available:
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 }
}
This outputs:
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"
}
Instead of just outputting this you should be able to iterate over the availability zones to set the instance type for the aws_instance
resource.
Alternatively you could filter the output to reduce it to just a list of the AZs that can offer the t3
instance family by changing the output to the following:
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" })
}
This outputs the following, skipping the availability zone that doesn't include the t3
instance family:
foo = [
"us-east-1a",
"us-east-1b",
"us-east-1c",
"us-east-1d",
"us-east-1f",
]
来源:https://stackoverflow.com/questions/63969173/terraform-how-to-request-aws-ec2-instances-only-in-zones-where-the-requested-in