From ae94d1f5492d79d2f6e33e37fa508a6b380166b4 Mon Sep 17 00:00:00 2001 From: Miguel Harmant Date: Tue, 12 Nov 2024 11:19:50 -0500 Subject: [PATCH] Adds capacity reservation module --- modules/capacity-reservation/main.tf | 71 +++++++++++++++++++++++ modules/capacity-reservation/outputs.tf | 0 modules/capacity-reservation/variables.tf | 21 +++++++ 3 files changed, 92 insertions(+) create mode 100644 modules/capacity-reservation/main.tf create mode 100644 modules/capacity-reservation/outputs.tf create mode 100644 modules/capacity-reservation/variables.tf diff --git a/modules/capacity-reservation/main.tf b/modules/capacity-reservation/main.tf new file mode 100644 index 00000000..0ec6b351 --- /dev/null +++ b/modules/capacity-reservation/main.tf @@ -0,0 +1,71 @@ +locals { + capacity_reservations = merge(flatten([ + for ng_name, ng in var.node_groups : [ + for az_id in ng.availability_zone_ids : { + for type in ng.instance_types : "${type}-${az_id}" => { + capacity = ng.capacity + instance_type = type + az = data.aws_availability_zone.zone_ids[az_id].name + } + } + ] + ])...) + zone_ids = toset(flatten([for ng in var.node_groups : + ng.availability_zone_ids + ])) + + instance_types = toset([for cr in local.capacity_reservations : cr.instance_type]) +} + +data "aws_availability_zone" "zone_ids" { + for_each = local.zone_ids + zone_id = each.key +} + + +data "aws_ec2_instance_type_offerings" "this" { + for_each = local.instance_types + + filter { + name = "instance-type" + values = [each.key] + } + + location_type = "availability-zone" +} + + +resource "aws_ec2_capacity_reservation" "this" { + for_each = local.capacity_reservations + instance_type = each.value.instance_type + instance_platform = "Linux/UNIX" + availability_zone = each.value.az + instance_count = each.value.capacity + + lifecycle { + precondition { + condition = contains(data.aws_ec2_instance_type_offerings.this[each.value.instance_type].locations, each.value.az) + error_message = <<-EOM + Instance type ${each.value.instance_type} is NOT available in availability_zone ${each.value.az}. + available = ${jsonencode(data.aws_ec2_instance_type_offerings.this[each.value.instance_type].locations)} + EOM + } + } +} + +resource "terraform_data" "describe_capacity_reservation" { + for_each = aws_ec2_capacity_reservation.this + + provisioner "local-exec" { + command = <