When I create the VPC, I create a subnet in every availability zone.
Then, when I create my application, I want to input the ami and the type of instance (e.g. t3a.nano).
I want to avoid getting this error:
Error: Error launching source instance: Unsupported: Your requested instance type (a1.medium) is not supported in your requested Availability Zone (us-west-2b). Please retry your request by not specifying an Availability Zone or choosing us-west-2a, us-west-2c.
I am looking for a terraform module that can tell me if I can create my instance on this subnet given my ami and instance type.
I didn't find the terraform module one so I created my own. It is doing what I want but I wonder if there is a better way.
I put my code here. https://gitlab.com/korrident/terraform_calculate_ami_by_availability_zone
Quickly, I just use a data "external"
to call a bash
data "external" "subnet_available_for_ami" {
count = "${length(var.subnets_id)}"
program = ["bash", "${path.module}/check_subnet_ami.bash"]
query = {
ami = "${data.aws_ami.latest_ami.id}"
type = "${var.instance_type}"
subnet = "${var.subnets_id[count.index]}"
region = "${var.aws_region}"
profile = "${var.aws_profile}"
}
}
This script will call AWS CLI with a dry-run
aws --region=${REGION} ec2 run-instances \
--instance-type ${INSTANCE_TYPE} \
--image-id ${AMI} \
--subnet-id ${SUBNET_ID} \
--profile ${PROFILE} \
--dry-run
And in the end I filter the results to return a clean subnet list
locals {
uniq_answers = "${distinct(data.external.subnet_available_for_ami.*.result)}"
uniq_answers_filtered = [
for a in local.uniq_answers :
a if length(a) != 0
]
uniq_subnet_filtered = [
for a in local.uniq_answers_filtered :
a.subnet
]
}
Note that in the same script I also use the component aws_ami.
data "aws_ami" "latest_ami" {
Ideally, I would like this component to return me an ami available on my subnets.
There is no error, it works fine but is minimal. If nothing is found, the calling module will deal with it. The most problematic case is when there is only one result (I want my instances to be on multiple availability zones, not just one).
Has anyone found a better design?