carlos / platform Public

region HA P3b T2: add fixed-size groups and scoped IAM

Add opt-in fixed-capacity ASGs with pinned launch templates, initial launch
hooks, a module-local termination queue and scoped group IAM. Keep the
fixed plan unchanged through explicit count moves and full plan comparison.

Refuse unknown foreign identities in the plan gate, allowing only a
configuration-proven new group role. Add mock topology, IAM composition,
input refusal and fixed/group isolation tests. Boot content remains Task 3.
Co-Authored-By: GPT-6 Astra (codex) <noreply@openai.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev e089bba87b25348287483d06dacb1548a38ee873 parent ba06a96
16 files changed, +1,989 −41
  • infra/modules/region-host/group-init.sh.tftpl +12 −0
  • infra/modules/region-host/group.tf +272 −0
  • infra/modules/region-host/group_iam.tf +98 −0
  • infra/modules/region-host/main.tf +42 −20
  • infra/modules/region-host/outputs.tf +28 −5
  • infra/modules/region-host/tests/fixed-and-group/main.tf +69 −0
  • infra/modules/region-host/tests/fixed_state_unchanged.tftest.hcl +15 −13
  • infra/modules/region-host/tests/group.tftest.hcl +349 −0
  • infra/modules/region-host/tests/group_iam.tftest.hcl +190 −0
  • infra/modules/region-host/tests/group_isolation.tftest.hcl +92 −0
  • infra/modules/region-host/tests/instance_metadata.tftest.hcl +3 −3
  • infra/modules/region-host/variables.tf +108 −0
  • scripts/check-region-group-plan.py +59 −0
  • scripts/check_region_group_plan_test.py +51 −0
  • scripts/region_group_contract_test.py +242 −0
  • scripts/testdata/region-group-plan/fixed-resource-contract.json +359 −0

Intent

Attributed to this commit: 12.7 g CO₂e (1,453,114 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on region-ha-p3b-t2, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/infra/modules/region-host/group-init.sh.tftpl b/infra/modules/region-host/group-init.sh.tftpl
new file mode 100644
index 000000000..fecafb973
--- /dev/null
+++ b/infra/modules/region-host/group-init.sh.tftpl
@@ -0,0 +1,12 @@
+#!/bin/sh
+set -eu
+umask 077
+%{ for key, value in config ~}
+${key}=${value}
+export ${key}
+%{ endfor ~}
+
+# TASK 3: harden, fetch and verify bootstrap, write root configuration,
+# install the pinned release, then start the guarded group agent.
+# Until those steps exist, leave the initial launch hook to ABANDON.
+exit 1
diff --git a/infra/modules/region-host/group.tf b/infra/modules/region-host/group.tf
new file mode 100644
index 000000000..3b4ecbe76
--- /dev/null
+++ b/infra/modules/region-host/group.tf
@@ -0,0 +1,272 @@
+data "aws_partition" "current" {
+ count = var.mode == "group" ? 1 : 0
+}
+
+data "aws_ami" "group" {
+ count = var.mode == "group" ? 1 : 0
+ most_recent = false
+ filter {
+ name = "image-id"
+ values = [var.group_config.ami_id]
+ }
+ filter {
+ name = "architecture"
+ values = ["arm64"]
+ }
+}
+
+locals {
+ group_enabled = var.mode == "group"
+ group_tags = local.group_enabled ? {
+ "carlos:deployment" = var.group_config.deployment
+ "carlos:region" = var.group_config.region
+ } : {}
+ group_hook_name = "carlos-initial-launch"
+ group_vpc_cidrs = toset(concat([data.aws_vpc.host.cidr_block], [for association in data.aws_vpc.host.cidr_block_associations : association.cidr_block]))
+ group_ingress = !local.group_enabled ? null : var.group_ingress != null ? var.group_ingress : {
+ nlb_arn = "arn:${data.aws_partition.current[0].partition}:elasticloadbalancing:${data.aws_region.current.region}:${data.aws_caller_identity.current.account_id}:loadbalancer/${module.group_ingress[0].nlb_arn_suffix}"
+ nlb_security_group_id = module.group_ingress[0].nlb_security_group_id
+ target_group_arns = module.group_ingress[0].target_group_arns
+ public_ips = module.group_ingress[0].public_ips
+ }
+}
+
+# A caller reusing P3a ingress passes its outputs. Only a new region owns a child.
+module "group_ingress" {
+ count = local.group_enabled && var.group_ingress == null ? 1 : 0
+ source = "./ingress"
+ name = var.name
+ vpc_id = var.vpc_id
+ zones = var.group_zones
+ target_vpc_cidrs = local.group_vpc_cidrs
+ expected_targets = var.box_count
+}
+
+data "aws_subnets" "group" {
+ for_each = local.group_enabled ? var.group_zones : {}
+ filter {
+ name = "subnet-id"
+ values = [each.value.subnet_id]
+ }
+ filter {
+ name = "vpc-id"
+ values = [var.vpc_id]
+ }
+ filter {
+ name = "availability-zone"
+ values = [each.key]
+ }
+}
+
+data "aws_route_table" "group" {
+ for_each = local.group_enabled ? var.group_zones : {}
+ subnet_id = each.value.subnet_id
+ vpc_id = var.vpc_id
+}
+
+data "aws_lb" "group" {
+ count = local.group_enabled && var.group_ingress != null ? 1 : 0
+ arn = var.group_ingress.nlb_arn
+}
+
+data "aws_lb_target_group" "group_http" {
+ count = local.group_enabled && var.group_ingress != null ? 1 : 0
+ arn = var.group_ingress.target_group_arns["80"]
+}
+
+data "aws_lb_target_group" "group_https" {
+ count = local.group_enabled && var.group_ingress != null ? 1 : 0
+ arn = var.group_ingress.target_group_arns["443"]
+}
+
+data "aws_eip" "group" {
+ for_each = local.group_enabled && var.group_ingress != null ? var.group_zones : {}
+ id = each.value.allocation_id
+}
+
+resource "aws_security_group" "group" {
+ count = local.group_enabled ? 1 : 0
+ name = var.name
+ description = var.sg_description
+ vpc_id = var.vpc_id
+ dynamic "ingress" {
+ for_each = toset([80, 443])
+ content {
+ ipv6_cidr_blocks = []
+ from_port = ingress.value
+ to_port = ingress.value
+ protocol = "tcp"
+ security_groups = [local.group_ingress.nlb_security_group_id]
+ }
+ }
+ ingress {
+ ipv6_cidr_blocks = []
+ from_port = 443
+ to_port = 443
+ protocol = "tcp"
+ cidr_blocks = ["0.0.0.0/0"]
+ }
+ ingress {
+ ipv6_cidr_blocks = []
+ from_port = 443
+ to_port = 443
+ protocol = "tcp"
+ cidr_blocks = local.group_vpc_cidrs
+ }
+ egress {
+ from_port = 0
+ to_port = 0
+ protocol = "-1"
+ cidr_blocks = ["0.0.0.0/0"]
+ }
+ lifecycle {
+ precondition {
+ condition = alltrue([for az, zone in var.group_zones : contains(data.aws_subnets.group[az].ids, zone.subnet_id)])
+ error_message = "each group subnet must belong to its named zone and VPC"
+ }
+ precondition {
+ condition = alltrue([for table in data.aws_route_table.group : anytrue([for route in table.routes : route.cidr_block == "0.0.0.0/0" && startswith(route.gateway_id, "igw-")])])
+ error_message = "each group subnet must have a public route through an internet gateway"
+ }
+ precondition {
+ condition = var.group_ingress == null ? true : (
+ data.aws_lb.group[0].vpc_id == var.vpc_id && !data.aws_lb.group[0].internal &&
+ data.aws_lb.group[0].load_balancer_type == "network" && data.aws_lb.group[0].ip_address_type == "ipv4" &&
+ data.aws_lb.group[0].enable_cross_zone_load_balancing &&
+ data.aws_lb.group[0].security_groups == toset([var.group_ingress.nlb_security_group_id]) &&
+ { for zone in data.aws_lb.group[0].subnet_mapping : zone.subnet_id => zone.allocation_id } == { for zone in var.group_zones : zone.subnet_id => zone.allocation_id } &&
+ alltrue([for az, eip in data.aws_eip.group : eip.public_ip == var.group_ingress.public_ips[az]])
+ )
+ error_message = "existing ingress must match the group VPC, enabled zones, EIPs and NLB security group"
+ }
+ precondition {
+ condition = var.group_ingress == null ? true : alltrue([for port, tg in { "80" = data.aws_lb_target_group.group_http[0], "443" = data.aws_lb_target_group.group_https[0] } :
+ tg.vpc_id == var.vpc_id && tg.port == tonumber(port) && tg.protocol == "TCP" && tg.target_type == "instance" && tg.preserve_client_ip == "true" && tg.load_balancer_arns == toset([var.group_ingress.nlb_arn])
+ ])
+ error_message = "existing target groups must preserve client IPs and serve TCP 80 and 443 in the group VPC through the selected NLB"
+ }
+ }
+}
+
+resource "aws_launch_template" "group" {
+ count = local.group_enabled ? 1 : 0
+ name = var.name
+ image_id = var.group_config.ami_id
+ instance_type = var.instance_type
+ default_version = 1
+ iam_instance_profile {
+ name = aws_iam_instance_profile.host.name
+ }
+ network_interfaces {
+ associate_public_ip_address = true
+ delete_on_termination = true
+ security_groups = [aws_security_group.group[0].id]
+ }
+ metadata_options {
+ http_endpoint = "enabled"
+ http_tokens = "required"
+ http_put_response_hop_limit = 1
+ }
+ block_device_mappings {
+ device_name = data.aws_ami.group[0].root_device_name
+ ebs {
+ volume_size = var.root_volume_size
+ volume_type = "gp3"
+ encrypted = true
+ delete_on_termination = true
+ }
+ }
+ user_data = base64encode(templatefile("${path.module}/group-init.sh.tftpl", {
+ # POSIX single-quote escaping keeps even provider-computed values inert.
+ config = { for key, value in {
+ CARLOS_DEPLOYMENT = var.group_config.deployment
+ CARLOS_DEPLOYMENT_BUCKET = trimprefix(var.deployment_bucket_arn, "arn:${data.aws_partition.current[0].partition}:s3:::")
+ CARLOS_REGION = var.group_config.region
+ CARLOS_PLACEMENT_REGION = var.group_config.placement_region
+ AWS_REGION = data.aws_region.current.region
+ CARLOS_POOLS = join(",", sort(tolist(var.group_config.pools)))
+ CARLOS_BOOTSTRAP_OBJECT_KEY = "${local.group_ssm_path}/boot/bootstrap-object"
+ CARLOS_BOOTSTRAP_HASH_KEY = "${local.group_ssm_path}/boot/bootstrap-sha256"
+ CARLOS_INGRESS_KEY = "${local.group_ssm_path}/boot/ingress"
+ CARLOS_GROUP_NAME = var.name
+ CARLOS_LAUNCH_HOOK_NAME = local.group_hook_name
+ CARLOS_TERMINATION_QUEUE_URL = aws_sqs_queue.terminations.id
+ CARLOS_RELEASE = var.group_config.release
+ } : key => "'${replace(value, "'", "'\"'\"'")}'" }
+ }))
+ tags = local.group_tags
+ lifecycle {
+ precondition {
+ condition = data.aws_ami.group[0].root_device_type == "ebs" && can(regex("^/dev/[a-zA-Z0-9]+$", data.aws_ami.group[0].root_device_name))
+ error_message = "the pinned group AMI must have an EBS root device"
+ }
+ }
+}
+
+resource "aws_autoscaling_group" "group" {
+ count = local.group_enabled ? 1 : 0
+ name = var.name
+ min_size = var.box_count
+ max_size = var.box_count
+ desired_capacity = var.box_count
+ vpc_zone_identifier = [for zone in var.group_zones : zone.subnet_id]
+ target_group_arns = values(local.group_ingress.target_group_arns)
+ health_check_type = "ELB"
+ health_check_grace_period = 60
+ suspended_processes = ["AZRebalance"]
+ enabled_metrics = ["GroupInServiceInstances", "GroupDesiredCapacity"]
+ metrics_granularity = "1Minute"
+ launch_template {
+ id = aws_launch_template.group[0].id
+ version = tostring(var.group_launch_template_version)
+ }
+ initial_lifecycle_hook {
+ name = local.group_hook_name
+ lifecycle_transition = "autoscaling:EC2_INSTANCE_LAUNCHING"
+ heartbeat_timeout = 900
+ default_result = "ABANDON"
+ }
+ dynamic "tag" {
+ for_each = merge(local.group_tags, { Name = var.name })
+ content {
+ key = tag.key
+ value = tag.value
+ propagate_at_launch = true
+ }
+ }
+ # The first launch must have its policy, queue selection and rule already.
+ depends_on = [
+ aws_iam_role_policy.group, aws_iam_role_policy.host_buckets,
+ aws_iam_role_policy.host_ssm_parameter_scope, aws_iam_role_policy.host_release_key_deny,
+ aws_iam_role_policy.host_route53, aws_iam_role_policy.host_steering,
+ aws_iam_role_policy.host_metrics, aws_iam_role_policy.host_terminations,
+ aws_iam_role_policy_attachment.host_ssm, aws_sqs_queue_policy.terminations,
+ aws_cloudwatch_event_target.terminations, aws_ssm_parameter.group_queue,
+ ]
+}
+
+resource "aws_ssm_parameter" "group_queue" {
+ count = local.group_enabled ? 1 : 0
+ name = "${local.group_ssm_path}/CARLOS_TERMINATION_QUEUE_URL"
+ type = "String"
+ value = aws_sqs_queue.terminations.id
+ tags = local.group_tags
+}
+
+# Only these fixed resources need addresses changed to support mode selection.
+moved {
+ from = aws_instance.host
+ to = aws_instance.host[0]
+}
+moved {
+ from = aws_eip.host
+ to = aws_eip.host[0]
+}
+moved {
+ from = aws_security_group.host
+ to = aws_security_group.host[0]
+}
+moved {
+ from = data.aws_ami.debian_arm64
+ to = data.aws_ami.debian_arm64[0]
+}
diff --git a/infra/modules/region-host/group_iam.tf b/infra/modules/region-host/group_iam.tf
new file mode 100644
index 000000000..c796f2049
--- /dev/null
+++ b/infra/modules/region-host/group_iam.tf
@@ -0,0 +1,98 @@
+locals {
+ group_ssm_path = local.group_enabled ? "/carlos/${var.group_config.deployment}/${var.group_config.region}" : ""
+ group_regional_arn = local.group_enabled ? "arn:${data.aws_partition.current[0].partition}:ssm:${data.aws_region.current.region}:${data.aws_caller_identity.current.account_id}:parameter${local.group_ssm_path}" : ""
+ group_shared_arn = local.group_enabled ? "arn:${data.aws_partition.current[0].partition}:ssm:${data.aws_region.current.region}:${data.aws_caller_identity.current.account_id}:parameter/carlos/${var.group_config.deployment}/shared" : ""
+ group_parameter_arns = [local.group_regional_arn, "${local.group_regional_arn}/*", local.group_shared_arn, "${local.group_shared_arn}/*"]
+ group_parameter_actions = ["ssm:GetParameter", "ssm:GetParameters", "ssm:GetParameterHistory", "ssm:GetParametersByPath"]
+ # Existing move consumers: laneProbe (moves/_lane/), retireOwnMoveState
+ # (move-snapshots/), and placeBuildState / generation selection (instances/).
+ # Version access stays in this region's data bucket, never sibling buckets.
+ group_version_prefixes = ["instances/*", "moves/*", "move-snapshots/*"]
+ group_bucket_statements = concat([
+ {
+ Effect = "Allow"
+ Action = ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"]
+ Resource = ["${var.deployment_bucket_arn}/*", "${var.data_bucket_arn}/*"]
+ },
+ {
+ Effect = "Allow"
+ Action = ["s3:ListBucket", "s3:GetBucketLocation"]
+ Resource = [var.deployment_bucket_arn, var.data_bucket_arn]
+ },
+ {
+ Effect = "Allow"
+ Action = ["s3:GetObjectVersion"]
+ Resource = ["${var.deployment_bucket_arn}/*", "${var.data_bucket_arn}/*"]
+ },
+ {
+ Sid = "RegionalMoveVersions"
+ Effect = "Allow"
+ Action = ["s3:DeleteObjectVersion"]
+ Resource = [for prefix in local.group_version_prefixes : "${var.data_bucket_arn}/${prefix}"]
+ },
+ {
+ Sid = "RegionalMoveVersionList"
+ Effect = "Allow"
+ Action = ["s3:ListBucketVersions"]
+ Resource = [var.data_bucket_arn]
+ Condition = { StringLike = { "s3:prefix" = local.group_version_prefixes } }
+ },
+ ],
+ [for arn in var.sibling_staging_arns : {
+ Effect = "Allow"
+ Action = ["s3:PutObject", "s3:DeleteObject"]
+ Resource = "${arn}/moves/*"
+ }],
+ [for arn in var.sibling_staging_arns : {
+ Effect = "Allow"
+ Action = ["s3:ListBucket"]
+ Resource = arn
+ Condition = { StringLike = { "s3:prefix" = "moves/*" } }
+ }]
+ )
+}
+
+resource "aws_iam_role_policy" "group" {
+ count = local.group_enabled ? 1 : 0
+ name = "${var.iam_name}-group"
+ role = aws_iam_role.host.id
+ policy = jsonencode({
+ Version = "2012-10-17"
+ Statement = [
+ {
+ Effect = "Allow"
+ Action = local.group_parameter_actions
+ Resource = local.group_parameter_arns
+ },
+ {
+ Effect = "Allow"
+ Action = ["kms:Decrypt"]
+ Resource = var.group_config.configuration_kms_key_arn
+ Condition = {
+ StringEquals = { "kms:ViaService" = "ssm.${data.aws_region.current.region}.${data.aws_partition.current[0].dns_suffix}" }
+ StringLike = { "kms:EncryptionContext:PARAMETER_ARN" = local.group_parameter_arns }
+ }
+ },
+ {
+ Effect = "Allow"
+ Action = ["autoscaling:CompleteLifecycleAction"]
+ Resource = "arn:${data.aws_partition.current[0].partition}:autoscaling:${data.aws_region.current.region}:${data.aws_caller_identity.current.account_id}:autoScalingGroup:*:autoScalingGroupName/${var.name}"
+ Condition = { StringEquals = {
+ "aws:ResourceTag/carlos:deployment" = var.group_config.deployment
+ "aws:ResourceTag/carlos:region" = var.group_config.region
+ } }
+ },
+ {
+ Effect = "Allow"
+ Action = ["ec2:DescribeInstances"]
+ Resource = "*"
+ Condition = { StringEquals = { "aws:RequestedRegion" = data.aws_region.current.region } }
+ },
+ {
+ Effect = "Deny"
+ Action = ["s3:PutObject", "s3:DeleteObject", "s3:DeleteObjectVersion", "s3:PutObjectTagging", "s3:DeleteObjectTagging", "s3:PutObjectVersionTagging", "s3:DeleteObjectVersionTagging"]
+ Resource = "${var.deployment_bucket_arn}/control/box-roles/*"
+ },
+ ]
+ })
+}
diff --git a/infra/modules/region-host/main.tf b/infra/modules/region-host/main.tf
index 0e206d0ea..ba9108366 100644
--- a/infra/modules/region-host/main.tf
+++ b/infra/modules/region-host/main.tf
@@ -12,6 +12,7 @@
data "aws_region" "current" {}
data "aws_ami" "debian_arm64" {
+ count = var.mode == "fixed" ? 1 : 0
most_recent = true
owners = [var.ami_owner]
filter {
@@ -73,6 +74,7 @@ locals {
}
resource "aws_security_group" "host" {
+ count = var.mode == "fixed" ? 1 : 0
name = var.name
description = var.sg_description
# Null = the region's default VPC, which is what this module did before it
@@ -137,6 +139,24 @@ resource "aws_security_group" "host" {
}
resource "aws_iam_role" "host" {
+ lifecycle {
+ precondition {
+ condition = var.mode == "fixed" ? (var.group_config == null && length(var.group_zones) == 0 && var.group_ingress == null) : (
+ can(regex("^vpc-[0-9a-f]{17}$", var.vpc_id)) && var.subnet_id == null && var.group_config != null &&
+ var.root_volume_size >= 1 && floor(var.root_volume_size) == var.root_volume_size &&
+ var.user_data == "" && var.ssm_parameter_arn == "" &&
+ (var.group_ingress == null || alltrue([for zone in var.group_zones : zone.allocation_id != null])) &&
+ !var.relay && length(var.extra_ingress) == 0 && !var.enable_cost_explorer &&
+ var.console_mail_from == "" && var.console_mail_region == "" &&
+ var.store_bucket_prefix == "" && !var.store_scanning &&
+ var.scope_ssm_parameter_reads && var.deny_release_key_reads &&
+ (length(var.steering_zone_ids) == 0 || length(var.steering_record_names) > 0) &&
+ can(regex("^[a-zA-Z][a-zA-Z0-9-]{0,22}$", var.name)) &&
+ can(regex("^[a-zA-Z][a-zA-Z0-9-]{0,63}$", var.iam_name))
+ )
+ error_message = "group mode needs explicit VPC and group configuration, scoped SSM and steering, and no fixed subnet, custom user data, relay or console settings"
+ }
+ }
name = var.iam_name
assume_role_policy = jsonencode({
Version = "2012-10-17"
@@ -153,7 +173,7 @@ resource "aws_iam_role" "host" {
resource "aws_iam_role_policy" "host_buckets" {
name = "${var.iam_name}-buckets"
role = aws_iam_role.host.id
- policy = jsonencode({
+ policy = local.group_enabled ? jsonencode({ Version = "2012-10-17", Statement = local.group_bucket_statements }) : jsonencode({
Version = "2012-10-17"
# The two sibling-staging statement groups (instance-move spec, issue
# #331) are appended only when sibling_staging_arns is non-empty:
@@ -263,7 +283,7 @@ resource "aws_iam_role_policy" "host_route53" {
{
Effect = "Allow"
Action = ["route53:ChangeResourceRecordSets"]
- Resource = [for z in var.route53_zone_ids : "arn:aws:route53:::hostedzone/${z}"]
+ Resource = [for z in var.route53_zone_ids : "arn:${local.group_enabled ? data.aws_partition.current[0].partition : "aws"}:route53:::hostedzone/${z}"]
# The box may touch ONLY _acme-challenge TXT records, and only via the
# two operations the edge issues (UPSERT in present, DELETE in cleanup).
# Without these conditions a zone grant is the whole zone — apex, MX,
@@ -281,7 +301,7 @@ resource "aws_iam_role_policy" "host_route53" {
{
Effect = "Allow"
Action = ["route53:GetChange"]
- Resource = "arn:aws:route53:::change/*"
+ Resource = "arn:${local.group_enabled ? data.aws_partition.current[0].partition : "aws"}:route53:::change/*"
},
{
Effect = "Allow"
@@ -324,7 +344,7 @@ resource "aws_iam_role_policy" "host_steering" {
# through a CNAME in the customer's own zone.
Effect = "Allow"
Action = ["route53:ChangeResourceRecordSets"]
- Resource = [for z in var.steering_zone_ids : "arn:aws:route53:::hostedzone/${z}"]
+ Resource = [for z in var.steering_zone_ids : "arn:${local.group_enabled ? data.aws_partition.current[0].partition : "aws"}:route53:::hostedzone/${z}"]
Condition = merge(
{
"ForAllValues:StringEquals" = {
@@ -345,7 +365,7 @@ resource "aws_iam_role_policy" "host_steering" {
# decoration on this action, which is worse than saying so here.
Effect = "Allow"
Action = ["route53:ListResourceRecordSets"]
- Resource = [for z in var.steering_zone_ids : "arn:aws:route53:::hostedzone/${z}"]
+ Resource = [for z in var.steering_zone_ids : "arn:${local.group_enabled ? data.aws_partition.current[0].partition : "aws"}:route53:::hostedzone/${z}"]
},
{
# Health checks are NOT zone-scoped and Route53 supports NO
@@ -377,7 +397,7 @@ resource "aws_iam_role_policy" "host_steering" {
# ListTagsForResource grants it nothing.
"route53:ListTagsForResources",
]
- Resource = "arn:aws:route53:::healthcheck/*"
+ Resource = "arn:${local.group_enabled ? data.aws_partition.current[0].partition : "aws"}:route53:::healthcheck/*"
},
]
})
@@ -431,7 +451,7 @@ resource "aws_iam_role_policy" "host_metrics" {
# whose recovery path is the thing that just broke.
resource "aws_iam_role_policy_attachment" "host_ssm" {
role = aws_iam_role.host.name
- policy_arn = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"
+ policy_arn = "arn:${local.group_enabled ? data.aws_partition.current[0].partition : "aws"}:iam::aws:policy/AmazonSSMManagedInstanceCore"
}
# ...and the hole that comes with it, closed.
@@ -468,7 +488,7 @@ resource "aws_iam_role_policy" "host_ssm_parameter_scope" {
"ssm:GetParameterHistory",
"ssm:GetParametersByPath",
]
- NotResource = [var.ssm_parameter_arn]
+ NotResource = local.group_enabled ? local.group_parameter_arns : [var.ssm_parameter_arn]
},
]
})
@@ -511,17 +531,17 @@ resource "aws_iam_role_policy" "host_release_key_deny" {
"ssm:GetParameters",
"ssm:GetParameterHistory",
]
- Resource = "arn:aws:ssm:*:${data.aws_caller_identity.current.account_id}:parameter/carlos/release-key"
+ Resource = "arn:${local.group_enabled ? data.aws_partition.current[0].partition : "aws"}:ssm:*:${data.aws_caller_identity.current.account_id}:parameter/carlos/release-key"
},
{
Sid = "DenyReleaseKeyAncestorPathReads"
Effect = "Deny"
Action = "ssm:GetParametersByPath"
Resource = [
- "arn:aws:ssm:*:${data.aws_caller_identity.current.account_id}:parameter/carlos",
- "arn:aws:ssm:*:${data.aws_caller_identity.current.account_id}:parameter/carlos/",
- "arn:aws:ssm:*:${data.aws_caller_identity.current.account_id}:parameter",
- "arn:aws:ssm:*:${data.aws_caller_identity.current.account_id}:parameter/",
+ "arn:${local.group_enabled ? data.aws_partition.current[0].partition : "aws"}:ssm:*:${data.aws_caller_identity.current.account_id}:parameter/carlos",
+ "arn:${local.group_enabled ? data.aws_partition.current[0].partition : "aws"}:ssm:*:${data.aws_caller_identity.current.account_id}:parameter/carlos/",
+ "arn:${local.group_enabled ? data.aws_partition.current[0].partition : "aws"}:ssm:*:${data.aws_caller_identity.current.account_id}:parameter",
+ "arn:${local.group_enabled ? data.aws_partition.current[0].partition : "aws"}:ssm:*:${data.aws_caller_identity.current.account_id}:parameter/",
]
},
]
@@ -534,13 +554,14 @@ resource "aws_iam_instance_profile" "host" {
}
resource "aws_instance" "host" {
- ami = data.aws_ami.debian_arm64.id
+ count = var.mode == "fixed" ? 1 : 0
+ ami = data.aws_ami.debian_arm64[0].id
instance_type = var.instance_type
# Null = the default VPC's default subnet, EC2's own behaviour and this
# module's original one. The security group's precondition guarantees this
# is only null when a default VPC exists to hold it.
subnet_id = var.subnet_id
- vpc_security_group_ids = [aws_security_group.host.id]
+ vpc_security_group_ids = [aws_security_group.host[0].id]
iam_instance_profile = aws_iam_instance_profile.host.name
user_data = var.user_data
user_data_replace_on_change = false
@@ -578,15 +599,16 @@ resource "aws_instance" "host" {
}
resource "aws_eip" "host" {
+ count = var.mode == "fixed" ? 1 : 0
domain = "vpc"
- instance = aws_instance.host.id
+ instance = aws_instance.host[0].id
tags = { Name = var.name }
}
# HA ladder rung 0 (2026-08-12 spec): system-status failure recovers the
# instance onto healthy hardware, keeping instance id, EIP and volumes.
resource "aws_cloudwatch_metric_alarm" "host_auto_recover" {
- count = var.enable_auto_recovery ? 1 : 0
+ count = var.mode == "fixed" && var.enable_auto_recovery ? 1 : 0
alarm_name = "${var.name}-auto-recover"
alarm_description = "EC2 system-status-check failure — auto-recovers ${var.name} onto healthy hardware."
namespace = "AWS/EC2"
@@ -598,7 +620,7 @@ resource "aws_cloudwatch_metric_alarm" "host_auto_recover" {
comparison_operator = "GreaterThanOrEqualToThreshold"
alarm_actions = ["arn:aws:automate:${data.aws_region.current.region}:ec2:recover"]
dimensions = {
- InstanceId = aws_instance.host.id
+ InstanceId = aws_instance.host[0].id
}
tags = { Name = "${var.name}-auto-recover" }
}
@@ -627,7 +649,7 @@ resource "aws_sns_topic_subscription" "alerts_email" {
}
resource "aws_cloudwatch_metric_alarm" "host_memory_low" {
- count = var.alerts_email != "" ? 1 : 0
+ count = var.mode == "fixed" && var.alerts_email != "" ? 1 : 0
alarm_name = "${var.name}-memory-low"
alarm_description = "MemAvailable below 15% for 3 minutes on ${var.name} — a tenant is eating the box; see the memory-pressure spec §4 for what to look at."
namespace = "Carlos/Host"
@@ -642,7 +664,7 @@ resource "aws_cloudwatch_metric_alarm" "host_memory_low" {
alarm_actions = [aws_sns_topic.alerts[0].arn]
ok_actions = [aws_sns_topic.alerts[0].arn]
dimensions = {
- InstanceId = aws_instance.host.id
+ InstanceId = aws_instance.host[0].id
}
tags = { Name = "${var.name}-memory-low" }
}
diff --git a/infra/modules/region-host/outputs.tf b/infra/modules/region-host/outputs.tf
index 3ddaabd82..3dbb05578 100644
--- a/infra/modules/region-host/outputs.tf
+++ b/infra/modules/region-host/outputs.tf
@@ -1,16 +1,16 @@
output "eip_public_ip" {
description = "Public IP of the host's Elastic IP — the address DNS records point at."
- value = aws_eip.host.public_ip
+ value = var.mode == "fixed" ? aws_eip.host[0].public_ip : null
}
output "instance_id" {
description = "EC2 instance id of the host."
- value = aws_instance.host.id
+ value = var.mode == "fixed" ? aws_instance.host[0].id : null
}
output "security_group_id" {
description = "Security group id of the host — useful for sibling services that admit traffic from the fleet only."
- value = aws_security_group.host.id
+ value = var.mode == "fixed" ? aws_security_group.host[0].id : aws_security_group.group[0].id
}
output "role_arn" {
@@ -24,8 +24,8 @@ output "role_name" {
}
output "ami_id" {
- description = "Resolved AMI id (most recent matching image) — reusable by sibling boxes in the same root."
- value = data.aws_ami.debian_arm64.id
+ description = "AMI ID selected for this host or group."
+ value = var.mode == "fixed" ? data.aws_ami.debian_arm64[0].id : var.group_config.ami_id
}
output "store_user_boundary_arn" {
@@ -42,3 +42,26 @@ output "termination_queue_url" {
description = "The queue that receives this region's EC2 terminated events."
value = aws_sqs_queue.terminations.id
}
+
+output "group_name" {
+ value = var.mode == "group" ? aws_autoscaling_group.group[0].name : null
+}
+output "group_arn" {
+ value = var.mode == "group" ? aws_autoscaling_group.group[0].arn : null
+}
+output "group_launch_template_id" {
+ value = var.mode == "group" ? aws_launch_template.group[0].id : null
+}
+output "group_launch_template_version" {
+ value = var.mode == "group" ? var.group_launch_template_version : null
+}
+output "group_ingress" {
+ value = local.group_ingress
+}
+output "group_boot_parameters" {
+ value = var.mode == "group" ? {
+ bootstrap_object = "${local.group_ssm_path}/boot/bootstrap-object"
+ bootstrap_sha256 = "${local.group_ssm_path}/boot/bootstrap-sha256"
+ ingress = "${local.group_ssm_path}/boot/ingress"
+ } : null
+}
diff --git a/infra/modules/region-host/tests/fixed-and-group/main.tf b/infra/modules/region-host/tests/fixed-and-group/main.tf
new file mode 100644
index 000000000..5aff0379c
--- /dev/null
+++ b/infra/modules/region-host/tests/fixed-and-group/main.tf
@@ -0,0 +1,69 @@
+locals {
+ fixture = {
+ mode = "group"
+ name = "carlos-dev-ie-group"
+ iam_name = "carlos-dev-ie-group"
+ sg_description = "test group"
+ instance_type = "t4g.micro"
+ root_volume_size = 20
+ user_data = ""
+ deployment_bucket_arn = "arn:aws:s3:::carlos-dev-platform"
+ data_bucket_arn = "arn:aws:s3:::carlos-dev-ie"
+ ssm_parameter_arn = ""
+ vpc_id = "vpc-0123456789abcdef0"
+ box_count = 2
+ group_config = {
+ deployment = "dev"
+ region = "ie"
+ placement_region = "ie"
+ pools = ["default"]
+ ami_id = "ami-0123456789abcdef0"
+ release = "v0.100.0"
+ configuration_kms_key_arn = "arn:aws:kms:eu-west-1:123456789012:key/00000000-0000-0000-0000-000000000001"
+ }
+ group_zones = {
+ eu-west-1a = { subnet_id = "subnet-00000000000000001", allocation_id = "eipalloc-00000000000000001" }
+ eu-west-1b = { subnet_id = "subnet-00000000000000002", allocation_id = "eipalloc-00000000000000002" }
+ }
+ group_ingress = {
+ nlb_arn = "arn:aws:elasticloadbalancing:eu-west-1:123456789012:loadbalancer/net/test/1234"
+ nlb_security_group_id = "sg-0123456789abcdef0"
+ target_group_arns = {
+ "80" = "arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/test-80/1234"
+ "443" = "arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/test-443/1234"
+ }
+ public_ips = { eu-west-1a = "198.51.100.10", eu-west-1b = "198.51.100.10" }
+ }
+ }
+}
+
+module "fixed" {
+ source = "../.."
+ name = "carlos-dev-fixed"
+ iam_name = "carlos-dev-fixed"
+ sg_description = "fixed fixture"
+ instance_type = "t4g.small"
+ root_volume_size = 20
+ user_data = "#!/bin/sh\n"
+ deployment_bucket_arn = "arn:aws:s3:::carlos-dev-platform"
+ data_bucket_arn = "arn:aws:s3:::carlos-dev-ie"
+ ssm_parameter_arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/carlos/*"
+}
+module "group" {
+ source = "../.."
+ name = local.fixture.name
+ sg_description = local.fixture.sg_description
+ iam_name = local.fixture.iam_name
+ instance_type = local.fixture.instance_type
+ root_volume_size = local.fixture.root_volume_size
+ user_data = local.fixture.user_data
+ deployment_bucket_arn = local.fixture.deployment_bucket_arn
+ data_bucket_arn = local.fixture.data_bucket_arn
+ ssm_parameter_arn = local.fixture.ssm_parameter_arn
+ mode = local.fixture.mode
+ vpc_id = local.fixture.vpc_id
+ box_count = local.fixture.box_count
+ group_config = local.fixture.group_config
+ group_zones = local.fixture.group_zones
+ group_ingress = local.fixture.group_ingress
+}
diff --git a/infra/modules/region-host/tests/fixed_state_unchanged.tftest.hcl b/infra/modules/region-host/tests/fixed_state_unchanged.tftest.hcl
index ca68ecb17..a6548d44c 100644
--- a/infra/modules/region-host/tests/fixed_state_unchanged.tftest.hcl
+++ b/infra/modules/region-host/tests/fixed_state_unchanged.tftest.hcl
@@ -1,6 +1,8 @@
# Plan-time tests for the host instance's metadata service settings.
# mock_provider means no AWS account and no credentials.
-mock_provider "aws" {}
+mock_provider "aws" {
+ mock_data "aws_region" { defaults = { region = "eu-west-1" } }
+}
override_data {
target = data.aws_vpcs.default
@@ -60,16 +62,16 @@ run "fixed_state_unchanged" {
command = plan
assert {
condition = (
- aws_instance.host.instance_type == "t4g.small" &&
- aws_instance.host.iam_instance_profile == "carlos-test-host" &&
- aws_instance.host.vpc_security_group_ids == toset(["sg-0123456789abcdef0"]) &&
- aws_instance.host.user_data == "#!/bin/sh\n" &&
- !aws_instance.host.user_data_replace_on_change &&
- aws_instance.host.root_block_device[0].volume_size == 20 &&
- aws_instance.host.root_block_device[0].volume_type == "gp3" &&
- aws_instance.host.root_block_device[0].encrypted &&
- aws_instance.host.root_block_device[0].delete_on_termination &&
- aws_eip.host.instance == "i-0123456789abcdef0" &&
+ aws_instance.host[0].instance_type == "t4g.small" &&
+ aws_instance.host[0].iam_instance_profile == "carlos-test-host" &&
+ aws_instance.host[0].vpc_security_group_ids == toset(["sg-0123456789abcdef0"]) &&
+ aws_instance.host[0].user_data == "#!/bin/sh\n" &&
+ !aws_instance.host[0].user_data_replace_on_change &&
+ aws_instance.host[0].root_block_device[0].volume_size == 20 &&
+ aws_instance.host[0].root_block_device[0].volume_type == "gp3" &&
+ aws_instance.host[0].root_block_device[0].encrypted &&
+ aws_instance.host[0].root_block_device[0].delete_on_termination &&
+ aws_eip.host[0].instance == "i-0123456789abcdef0" &&
aws_iam_instance_profile.host.role == "carlos-test-host"
)
error_message = "fixed instance, profile, security group and volume contract changed"
@@ -87,8 +89,8 @@ run "fixed_state_unchanged" {
error_message = "legacy fixed outputs changed"
}
assert {
- condition = length(aws_security_group.host.ingress) == 2 && alltrue([
- for rule in aws_security_group.host.ingress :
+ condition = length(aws_security_group.host[0].ingress) == 2 && alltrue([
+ for rule in aws_security_group.host[0].ingress :
rule.protocol == "tcp" && contains([80, 443], rule.from_port) &&
rule.to_port == rule.from_port && rule.cidr_blocks == tolist(["0.0.0.0/0"])
])
diff --git a/infra/modules/region-host/tests/group.tftest.hcl b/infra/modules/region-host/tests/group.tftest.hcl
new file mode 100644
index 000000000..36128bc96
--- /dev/null
+++ b/infra/modules/region-host/tests/group.tftest.hcl
@@ -0,0 +1,349 @@
+mock_provider "aws" {
+ mock_resource "aws_launch_template" { defaults = { id = "lt-0123456789abcdef0" } }
+ mock_resource "aws_security_group" { defaults = { id = "sg-0123456789abcdef1" } }
+}
+override_data {
+ target = data.aws_region.current
+ values = { region = "eu-west-1" }
+}
+override_data {
+ target = data.aws_partition.current
+ values = { partition = "aws", dns_suffix = "amazonaws.com" }
+}
+override_data {
+ target = data.aws_caller_identity.current
+ values = { account_id = "123456789012" }
+}
+override_data {
+ target = data.aws_vpc.host
+ values = { cidr_block = "10.0.0.0/16", cidr_block_associations = [] }
+}
+override_data {
+ target = data.aws_subnets.group
+ values = { ids = ["subnet-00000000000000001", "subnet-00000000000000002"] }
+}
+override_data {
+ target = data.aws_route_table.group
+ values = { routes = [{ cidr_block = "0.0.0.0/0", gateway_id = "igw-0123456789abcdef0", carrier_gateway_id = "", core_network_arn = "", destination_prefix_list_id = "", egress_only_gateway_id = "", instance_id = "", ipv6_cidr_block = "", local_gateway_id = "", nat_gateway_id = "", network_interface_id = "", odb_network_arn = "", transit_gateway_id = "", vpc_endpoint_id = "", vpc_peering_connection_id = "" }] }
+}
+override_data {
+ target = data.aws_lb.group
+ values = {
+ vpc_id = "vpc-0123456789abcdef0"
+ internal = false
+ load_balancer_type = "network"
+ ip_address_type = "ipv4"
+ enable_cross_zone_load_balancing = true
+ security_groups = ["sg-0123456789abcdef0"]
+ subnet_mapping = [
+ { subnet_id = "subnet-00000000000000001", allocation_id = "eipalloc-00000000000000001", ipv6_address = "", outpost_id = "", private_ipv4_address = "" },
+ { subnet_id = "subnet-00000000000000002", allocation_id = "eipalloc-00000000000000002", ipv6_address = "", outpost_id = "", private_ipv4_address = "" }
+ ]
+ }
+}
+override_data {
+ target = data.aws_lb_target_group.group_http
+ values = { vpc_id = "vpc-0123456789abcdef0", port = 80, protocol = "TCP", target_type = "instance", load_balancer_arns = ["arn:aws:elasticloadbalancing:eu-west-1:123456789012:loadbalancer/net/test/1234"], preserve_client_ip = "true" }
+}
+override_data {
+ target = data.aws_lb_target_group.group_https
+ values = { vpc_id = "vpc-0123456789abcdef0", port = 443, protocol = "TCP", target_type = "instance", load_balancer_arns = ["arn:aws:elasticloadbalancing:eu-west-1:123456789012:loadbalancer/net/test/1234"], preserve_client_ip = "true" }
+}
+override_data {
+ target = data.aws_eip.group
+ values = { public_ip = "198.51.100.10" }
+}
+override_resource {
+ target = aws_sqs_queue.terminations
+ values = { arn = "arn:aws:sqs:eu-west-1:123456789012:carlos-dev-ie-group-terminations", id = "https://sqs.eu-west-1.amazonaws.com/123456789012/carlos-dev-ie-group-terminations" }
+}
+override_resource {
+ target = aws_cloudwatch_event_rule.terminations
+ values = { arn = "arn:aws:events:eu-west-1:123456789012:rule/carlos-dev-ie-group-terminations" }
+}
+override_resource {
+ target = aws_iam_role.host
+ values = { id = "carlos-dev-ie-group", arn = "arn:aws:iam::123456789012:role/carlos-dev-ie-group" }
+}
+variables {
+ mode = "group"
+ name = "carlos-dev-ie-group"
+ iam_name = "carlos-dev-ie-group"
+ sg_description = "test group"
+ instance_type = "t4g.micro"
+ root_volume_size = 20
+ user_data = ""
+ deployment_bucket_arn = "arn:aws:s3:::carlos-dev-platform"
+ data_bucket_arn = "arn:aws:s3:::carlos-dev-ie"
+ ssm_parameter_arn = ""
+ vpc_id = "vpc-0123456789abcdef0"
+ box_count = 2
+ group_config = {
+ deployment = "dev"
+ region = "ie"
+ placement_region = "ie"
+ pools = ["default"]
+ ami_id = "ami-0123456789abcdef0"
+ release = "v0.100.0"
+ configuration_kms_key_arn = "arn:aws:kms:eu-west-1:123456789012:key/00000000-0000-0000-0000-000000000001"
+ }
+ group_zones = {
+ eu-west-1a = { subnet_id = "subnet-00000000000000001", allocation_id = "eipalloc-00000000000000001" }
+ eu-west-1b = { subnet_id = "subnet-00000000000000002", allocation_id = "eipalloc-00000000000000002" }
+ }
+ group_ingress = {
+ nlb_arn = "arn:aws:elasticloadbalancing:eu-west-1:123456789012:loadbalancer/net/test/1234"
+ nlb_security_group_id = "sg-0123456789abcdef0"
+ target_group_arns = {
+ "80" = "arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/test-80/1234"
+ "443" = "arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/test-443/1234"
+ }
+ public_ips = { eu-west-1a = "198.51.100.10", eu-west-1b = "198.51.100.10" }
+ }
+}
+
+run "group_shape" {
+ command = plan
+ assert {
+ condition = (
+ aws_autoscaling_group.group[0].min_size == 2 &&
+ aws_autoscaling_group.group[0].max_size == 2 &&
+ aws_autoscaling_group.group[0].desired_capacity == 2 &&
+ aws_autoscaling_group.group[0].enabled_metrics == toset(["GroupInServiceInstances", "GroupDesiredCapacity"]) &&
+ aws_autoscaling_group.group[0].metrics_granularity == "1Minute" &&
+ aws_autoscaling_group.group[0].health_check_type == "ELB" &&
+ aws_autoscaling_group.group[0].health_check_grace_period == 60 &&
+ aws_autoscaling_group.group[0].suspended_processes == toset(["AZRebalance"]) &&
+ aws_autoscaling_group.group[0].target_group_arns == toset(values(var.group_ingress.target_group_arns)) &&
+ aws_autoscaling_group.group[0].launch_template[0].version == "1" &&
+ aws_autoscaling_group.group[0].max_instance_lifetime == null &&
+ length(aws_autoscaling_group.group[0].instance_refresh) == 0 &&
+ length(aws_autoscaling_group.group[0].mixed_instances_policy) == 0 &&
+ length(aws_autoscaling_group.group[0].initial_lifecycle_hook) == 1 &&
+ one(aws_autoscaling_group.group[0].initial_lifecycle_hook).heartbeat_timeout == 900 &&
+ one(aws_autoscaling_group.group[0].initial_lifecycle_hook).default_result == "ABANDON" &&
+ one(aws_autoscaling_group.group[0].initial_lifecycle_hook).lifecycle_transition == "autoscaling:EC2_INSTANCE_LAUNCHING"
+ )
+ error_message = "group capacity, metrics, targets and initial hook must match the launch contract"
+ }
+ assert {
+ condition = (
+ aws_launch_template.group[0].image_id == var.group_config.ami_id &&
+ aws_launch_template.group[0].block_device_mappings[0].device_name == data.aws_ami.group[0].root_device_name &&
+ !data.aws_ami.group[0].most_recent &&
+ aws_launch_template.group[0].metadata_options[0].http_tokens == "required" &&
+ aws_launch_template.group[0].metadata_options[0].http_put_response_hop_limit == 1 &&
+ aws_launch_template.group[0].network_interfaces[0].associate_public_ip_address == "true" &&
+ aws_launch_template.group[0].block_device_mappings[0].ebs[0].encrypted == "true" &&
+ aws_launch_template.group[0].block_device_mappings[0].ebs[0].delete_on_termination == "true" &&
+ aws_launch_template.group[0].block_device_mappings[0].ebs[0].volume_type == "gp3" &&
+ aws_launch_template.group[0].block_device_mappings[0].ebs[0].volume_size == 20 &&
+ length(aws_instance.host) == 0 && length(aws_eip.host) == 0 &&
+ output.instance_id == null && output.eip_public_ip == null
+ )
+ error_message = "group launches must use pinned images, public IPv4, IMDSv2 and disposable encrypted roots"
+ }
+ assert {
+ condition = (
+ aws_sqs_queue.terminations.name == "carlos-dev-ie-group-terminations" &&
+ aws_sqs_queue.terminations.message_retention_seconds == 1209600 &&
+ aws_sqs_queue.terminations.sqs_managed_sse_enabled &&
+ aws_cloudwatch_event_target.terminations.arn == aws_sqs_queue.terminations.arn &&
+ aws_cloudwatch_event_target.terminations.rule == aws_cloudwatch_event_rule.terminations.name &&
+ jsondecode(aws_cloudwatch_event_rule.terminations.event_pattern).detail.state == ["terminated"] &&
+ aws_ssm_parameter.group_queue[0].name == "/carlos/dev/ie/CARLOS_TERMINATION_QUEUE_URL" &&
+ nonsensitive(aws_ssm_parameter.group_queue[0].value) == aws_sqs_queue.terminations.id
+ )
+ error_message = "the group must own its termination queue and regional queue selection"
+ }
+ assert {
+ condition = length(aws_security_group.group[0].ingress) == 4 && alltrue([
+ for rule in aws_security_group.group[0].ingress :
+ rule.protocol == "tcp" && rule.to_port == rule.from_port &&
+ length(rule.ipv6_cidr_blocks) == 0 && contains([80, 443], rule.from_port) &&
+ (rule.from_port != 80 || toset(rule.security_groups) == toset([var.group_ingress.nlb_security_group_id]))
+ ])
+ error_message = "group HTTP must require the NLB and no SSH or IPv6 ingress is allowed"
+ }
+}
+run "invalid_group_inputs" {
+ command = plan
+ variables { box_count = 1.5 }
+ expect_failures = [var.box_count]
+}
+run "invalid_group_subnet_mixture" {
+ command = plan
+ variables { subnet_id = "subnet-00000000000000001" }
+ expect_failures = [aws_iam_role.host]
+}
+run "invalid_group_console" {
+ command = plan
+ variables { enable_cost_explorer = true }
+ expect_failures = [aws_iam_role.host]
+}
+run "invalid_group_relay" {
+ command = plan
+ variables { relay = true }
+ expect_failures = [aws_iam_role.host]
+}
+run "transaction_open" {
+ command = plan
+ variables { group_transaction_open = true }
+ expect_failures = [var.group_transaction_open]
+}
+
+run "invalid_zero_count" {
+ command = plan
+ variables {
+ box_count = 0
+ }
+ expect_failures = [var.box_count]
+}
+
+run "invalid_unpinned_template" {
+ command = plan
+ variables {
+ group_launch_template_version = 0
+ }
+ expect_failures = [var.group_launch_template_version]
+}
+
+run "invalid_store_provisioning" {
+ command = plan
+ variables {
+ store_bucket_prefix = "carlos-store-"
+ }
+ expect_failures = [aws_iam_role.host]
+}
+
+run "invalid_store_scanning" {
+ command = plan
+ variables {
+ store_bucket_prefix = "carlos-store-"
+ store_scanning = true
+ }
+ expect_failures = [aws_iam_role.host]
+}
+
+run "invalid_console_mail" {
+ command = plan
+ variables {
+ console_mail_from = "mail@example.com"
+ console_mail_region = "eu-west-1"
+ }
+ expect_failures = [aws_iam_role.host]
+}
+
+run "invalid_ssm_deny_disabled" {
+ command = plan
+ variables {
+ scope_ssm_parameter_reads = false
+ }
+ expect_failures = [aws_iam_role.host]
+}
+
+run "invalid_release_deny_disabled" {
+ command = plan
+ variables {
+ deny_release_key_reads = false
+ }
+ expect_failures = [aws_iam_role.host]
+}
+
+run "invalid_steering_without_names" {
+ command = plan
+ variables {
+ steering_zone_ids = ["ZTESTSTEERING"]
+ }
+ expect_failures = [aws_iam_role.host]
+}
+
+run "invalid_custom_user_data" {
+ command = plan
+ variables {
+ user_data = "#!/bin/sh\ntrue"
+ }
+ expect_failures = [aws_iam_role.host]
+}
+
+run "invalid_fixed_with_group_config" {
+ command = plan
+ variables {
+ mode = "fixed"
+ subnet_id = "subnet-00000000000000001"
+ }
+ expect_failures = [aws_iam_role.host]
+}
+
+run "invalid_duplicate_eip" {
+ command = plan
+ variables {
+ group_zones = { eu-west-1a = { subnet_id = "subnet-00000000000000001", allocation_id = "eipalloc-00000000000000001" }, eu-west-1b = { subnet_id = "subnet-00000000000000002", allocation_id = "eipalloc-00000000000000001" } }
+ }
+ expect_failures = [var.group_zones]
+}
+
+run "wrong_vpc_subnets" {
+ command = plan
+ override_data {
+ target = data.aws_subnets.group
+ values = { ids = [] }
+ }
+ expect_failures = [aws_security_group.group]
+}
+run "private_subnets" {
+ command = plan
+ override_data {
+ target = data.aws_route_table.group
+ values = { routes = [] }
+ }
+ expect_failures = [aws_security_group.group]
+}
+run "wrong_vpc_target_group" {
+ command = plan
+ override_data {
+ target = data.aws_lb_target_group.group_http
+ values = { vpc_id = "vpc-00000000000000002" }
+ }
+ expect_failures = [aws_security_group.group]
+}
+run "new_ingress_owner" {
+ command = plan
+ variables { group_ingress = null }
+ override_module {
+ target = module.group_ingress
+ outputs = {
+ nlb_arn_suffix = "net/test/1234"
+ nlb_security_group_id = "sg-0123456789abcdef0"
+ target_group_arns = {
+ "80" = "arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/test-80/1234"
+ "443" = "arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/test-443/1234"
+ }
+ public_ips = { eu-west-1a = "198.51.100.10", eu-west-1b = "198.51.100.11" }
+ }
+ }
+ assert {
+ condition = length(module.group_ingress) == 1 && length(data.aws_lb.group) == 0 && aws_autoscaling_group.group[0].target_group_arns == toset(values(module.group_ingress[0].target_group_arns))
+ error_message = "new ingress must have one child owner and attach the group directly"
+ }
+}
+
+run "group_boot_quotes" {
+ command = plan
+ override_resource {
+ target = aws_sqs_queue.terminations
+ values = {
+ arn = "arn:aws:sqs:eu-west-1:123456789012:carlos-dev-ie-group-terminations"
+ id = "https://sqs.eu-west-1.amazonaws.com/123456789012/queue'$(printf injected)'"
+ }
+ }
+ assert {
+ condition = strcontains(base64decode(aws_launch_template.group[0].user_data), "TASK 3")
+ error_message = "the group template must reserve the boot steps for Task 3"
+ }
+}
+
+override_data {
+ target = data.aws_ami.group
+ values = { id = "ami-0123456789abcdef0", root_device_name = "/dev/xvda", root_device_type = "ebs" }
+}
diff --git a/infra/modules/region-host/tests/group_iam.tftest.hcl b/infra/modules/region-host/tests/group_iam.tftest.hcl
new file mode 100644
index 000000000..0b5529fc8
--- /dev/null
+++ b/infra/modules/region-host/tests/group_iam.tftest.hcl
@@ -0,0 +1,190 @@
+mock_provider "aws" {
+ mock_resource "aws_launch_template" { defaults = { id = "lt-0123456789abcdef0" } }
+ mock_resource "aws_security_group" { defaults = { id = "sg-0123456789abcdef1" } }
+}
+override_data {
+ target = data.aws_region.current
+ values = { region = "eu-west-1" }
+}
+override_data {
+ target = data.aws_partition.current
+ values = { partition = "aws", dns_suffix = "amazonaws.com" }
+}
+override_data {
+ target = data.aws_caller_identity.current
+ values = { account_id = "123456789012" }
+}
+override_data {
+ target = data.aws_vpc.host
+ values = { cidr_block = "10.0.0.0/16", cidr_block_associations = [] }
+}
+override_data {
+ target = data.aws_subnets.group
+ values = { ids = ["subnet-00000000000000001", "subnet-00000000000000002"] }
+}
+override_data {
+ target = data.aws_route_table.group
+ values = { routes = [{ cidr_block = "0.0.0.0/0", gateway_id = "igw-0123456789abcdef0", carrier_gateway_id = "", core_network_arn = "", destination_prefix_list_id = "", egress_only_gateway_id = "", instance_id = "", ipv6_cidr_block = "", local_gateway_id = "", nat_gateway_id = "", network_interface_id = "", odb_network_arn = "", transit_gateway_id = "", vpc_endpoint_id = "", vpc_peering_connection_id = "" }] }
+}
+override_data {
+ target = data.aws_lb.group
+ values = {
+ vpc_id = "vpc-0123456789abcdef0"
+ internal = false
+ load_balancer_type = "network"
+ ip_address_type = "ipv4"
+ enable_cross_zone_load_balancing = true
+ security_groups = ["sg-0123456789abcdef0"]
+ subnet_mapping = [
+ { subnet_id = "subnet-00000000000000001", allocation_id = "eipalloc-00000000000000001", ipv6_address = "", outpost_id = "", private_ipv4_address = "" },
+ { subnet_id = "subnet-00000000000000002", allocation_id = "eipalloc-00000000000000002", ipv6_address = "", outpost_id = "", private_ipv4_address = "" }
+ ]
+ }
+}
+override_data {
+ target = data.aws_lb_target_group.group_http
+ values = { vpc_id = "vpc-0123456789abcdef0", port = 80, protocol = "TCP", target_type = "instance", load_balancer_arns = ["arn:aws:elasticloadbalancing:eu-west-1:123456789012:loadbalancer/net/test/1234"], preserve_client_ip = "true" }
+}
+override_data {
+ target = data.aws_lb_target_group.group_https
+ values = { vpc_id = "vpc-0123456789abcdef0", port = 443, protocol = "TCP", target_type = "instance", load_balancer_arns = ["arn:aws:elasticloadbalancing:eu-west-1:123456789012:loadbalancer/net/test/1234"], preserve_client_ip = "true" }
+}
+override_data {
+ target = data.aws_eip.group
+ values = { public_ip = "198.51.100.10" }
+}
+override_resource {
+ target = aws_sqs_queue.terminations
+ values = { arn = "arn:aws:sqs:eu-west-1:123456789012:carlos-dev-ie-group-terminations", id = "https://sqs.eu-west-1.amazonaws.com/123456789012/carlos-dev-ie-group-terminations" }
+}
+override_resource {
+ target = aws_cloudwatch_event_rule.terminations
+ values = { arn = "arn:aws:events:eu-west-1:123456789012:rule/carlos-dev-ie-group-terminations" }
+}
+override_resource {
+ target = aws_iam_role.host
+ values = { id = "carlos-dev-ie-group", arn = "arn:aws:iam::123456789012:role/carlos-dev-ie-group" }
+}
+variables {
+ mode = "group"
+ name = "carlos-dev-ie-group"
+ iam_name = "carlos-dev-ie-group"
+ sg_description = "test group"
+ instance_type = "t4g.micro"
+ root_volume_size = 20
+ user_data = ""
+ deployment_bucket_arn = "arn:aws:s3:::carlos-dev-platform"
+ data_bucket_arn = "arn:aws:s3:::carlos-dev-ie"
+ ssm_parameter_arn = ""
+ vpc_id = "vpc-0123456789abcdef0"
+ box_count = 2
+ group_config = {
+ deployment = "dev"
+ region = "ie"
+ placement_region = "ie"
+ pools = ["default"]
+ ami_id = "ami-0123456789abcdef0"
+ release = "v0.100.0"
+ configuration_kms_key_arn = "arn:aws:kms:eu-west-1:123456789012:key/00000000-0000-0000-0000-000000000001"
+ }
+ group_zones = {
+ eu-west-1a = { subnet_id = "subnet-00000000000000001", allocation_id = "eipalloc-00000000000000001" }
+ eu-west-1b = { subnet_id = "subnet-00000000000000002", allocation_id = "eipalloc-00000000000000002" }
+ }
+ group_ingress = {
+ nlb_arn = "arn:aws:elasticloadbalancing:eu-west-1:123456789012:loadbalancer/net/test/1234"
+ nlb_security_group_id = "sg-0123456789abcdef0"
+ target_group_arns = {
+ "80" = "arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/test-80/1234"
+ "443" = "arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/test-443/1234"
+ }
+ public_ips = { eu-west-1a = "198.51.100.10", eu-west-1b = "198.51.100.10" }
+ }
+}
+
+run "group_iam_exact_scope" {
+ command = plan
+ assert {
+ condition = (
+ toset(jsondecode(aws_iam_role_policy.group[0].policy).Statement[0].Resource) == toset([
+ "arn:aws:ssm:eu-west-1:123456789012:parameter/carlos/dev/ie",
+ "arn:aws:ssm:eu-west-1:123456789012:parameter/carlos/dev/ie/*",
+ "arn:aws:ssm:eu-west-1:123456789012:parameter/carlos/dev/shared",
+ "arn:aws:ssm:eu-west-1:123456789012:parameter/carlos/dev/shared/*"
+ ]) &&
+ toset(jsondecode(aws_iam_role_policy.host_ssm_parameter_scope[0].policy).Statement[0].NotResource) == toset(jsondecode(aws_iam_role_policy.group[0].policy).Statement[0].Resource) &&
+ jsondecode(aws_iam_role_policy.group[0].policy).Statement[2].Resource == "arn:aws:autoscaling:eu-west-1:123456789012:autoScalingGroup:*:autoScalingGroupName/carlos-dev-ie-group" &&
+ jsondecode(aws_iam_role_policy.group[0].policy).Statement[2].Condition.StringEquals["aws:ResourceTag/carlos:deployment"] == "dev" &&
+ jsondecode(aws_iam_role_policy.group[0].policy).Statement[2].Condition.StringEquals["aws:ResourceTag/carlos:region"] == "ie" &&
+ jsondecode(aws_iam_role_policy.group[0].policy).Statement[3].Condition.StringEquals["aws:RequestedRegion"] == "eu-west-1"
+ )
+ error_message = "SSM, lifecycle completion and EC2 describes must stay scoped to this group"
+ }
+ assert {
+ condition = (
+ jsondecode(aws_iam_role_policy.group[0].policy).Statement[1].Resource == var.group_config.configuration_kms_key_arn &&
+ jsondecode(aws_iam_role_policy.group[0].policy).Statement[1].Condition.StringEquals["kms:ViaService"] == "ssm.eu-west-1.amazonaws.com" &&
+ toset(jsondecode(aws_iam_role_policy.group[0].policy).Statement[1].Condition.StringLike["kms:EncryptionContext:PARAMETER_ARN"]) == toset(jsondecode(aws_iam_role_policy.group[0].policy).Statement[0].Resource)
+ )
+ error_message = "configuration decryption must require the regional SSM service and matching parameter context"
+ }
+ assert {
+ condition = (
+ aws_iam_role_policy_attachment.host_ssm.policy_arn == "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore" &&
+ length(aws_iam_role_policy.host_release_key_deny) == 1 &&
+ length(aws_iam_role_policy.host_costexplorer) == 0 &&
+ length(aws_iam_role_policy.host_console_mail) == 0 &&
+ length(aws_iam_role_policy.host_store) == 0 &&
+ length(aws_iam_role_policy.host_store_scan) == 0 &&
+ length(aws_iam_role_policy.host_steering) == 0 &&
+ length(aws_iam_role_policy.host_route53) == 0 &&
+ jsondecode(aws_iam_role_policy.host_terminations.policy).Statement[0].Resource == aws_sqs_queue.terminations.arn &&
+ toset(jsondecode(aws_iam_role_policy.host_terminations.policy).Statement[0].Action) == toset(["sqs:ReceiveMessage", "sqs:DeleteMessage", "sqs:GetQueueAttributes"]) &&
+ jsondecode(aws_sqs_queue_policy.terminations.policy).Statement[1].Effect == "Deny" &&
+ jsondecode(aws_sqs_queue_policy.terminations.policy).Statement[1].Condition.ArnNotEquals["aws:SourceArn"] == aws_cloudwatch_event_rule.terminations.arn
+ )
+ error_message = "group inheritance must keep SSM and receive-only queue access without console grants"
+ }
+}
+run "group_no_control_writes" {
+ command = plan
+ assert {
+ condition = (
+ jsondecode(aws_iam_role_policy.group[0].policy).Statement[4].Effect == "Deny" &&
+ jsondecode(aws_iam_role_policy.group[0].policy).Statement[4].Resource == "arn:aws:s3:::carlos-dev-platform/control/box-roles/*" &&
+ toset(jsondecode(aws_iam_role_policy.group[0].policy).Statement[4].Action) == toset(["s3:PutObject", "s3:DeleteObject", "s3:DeleteObjectVersion", "s3:PutObjectTagging", "s3:DeleteObjectTagging", "s3:PutObjectVersionTagging", "s3:DeleteObjectVersionTagging"])
+ )
+ error_message = "group boxes must not write, delete or tag box roles"
+ }
+ assert {
+ condition = alltrue([for s in jsondecode(aws_iam_role_policy.host_buckets.policy).Statement : !contains(s.Action, "ec2:DescribeInstances") && (!contains(s.Action, "s3:DeleteObjectVersion") || !contains(s.Resource, "${var.data_bucket_arn}/*")) && (!contains(s.Action, "s3:ListBucketVersions") || try(length(s.Condition.StringLike["s3:prefix"]) == 3, false))])
+ error_message = "group bucket policy must not inherit broad version writes or console inventory"
+ }
+}
+
+run "group_dns_duties_enabled" {
+ command = plan
+ variables {
+ route53_zone_ids = ["ZTESTDNS"]
+ steering_zone_ids = ["ZTESTSTEERING"]
+ steering_record_names = ["*.example.com"]
+ }
+ assert {
+ condition = (
+ length(aws_iam_role_policy.host_route53) == 1 && length(aws_iam_role_policy.host_steering) == 1 &&
+ jsondecode(aws_iam_role_policy.host_route53[0].policy).Statement[0].Resource == ["arn:aws:route53:::hostedzone/ZTESTDNS"] &&
+ jsondecode(aws_iam_role_policy.host_route53[0].policy).Statement[0].Condition["ForAllValues:StringEquals"]["route53:ChangeResourceRecordSetsRecordTypes"] == ["TXT"] &&
+ jsondecode(aws_iam_role_policy.host_route53[0].policy).Statement[0].Condition["ForAllValues:StringLike"]["route53:ChangeResourceRecordSetsNormalizedRecordNames"] == ["_acme-challenge.*"] &&
+ jsondecode(aws_iam_role_policy.host_steering[0].policy).Statement[0].Resource == ["arn:aws:route53:::hostedzone/ZTESTSTEERING"] &&
+ jsondecode(aws_iam_role_policy.host_steering[0].policy).Statement[0].Condition["ForAllValues:StringLike"]["route53:ChangeResourceRecordSetsNormalizedRecordNames"] == ["*.example.com"] &&
+ jsondecode(aws_iam_role_policy.host_steering[0].policy).Statement[2].Resource == "*" &&
+ jsondecode(aws_iam_role_policy.host_steering[0].policy).Statement[3].Resource == "arn:aws:route53:::healthcheck/*"
+ )
+ error_message = "DNS duties must retain their zone, record-name and record-type bounds"
+ }
+}
+
+override_data {
+ target = data.aws_ami.group
+ values = { id = "ami-0123456789abcdef0", root_device_name = "/dev/xvda", root_device_type = "ebs" }
+}
diff --git a/infra/modules/region-host/tests/group_isolation.tftest.hcl b/infra/modules/region-host/tests/group_isolation.tftest.hcl
new file mode 100644
index 000000000..539400bd5
--- /dev/null
+++ b/infra/modules/region-host/tests/group_isolation.tftest.hcl
@@ -0,0 +1,92 @@
+mock_provider "aws" {
+ mock_data "aws_region" { defaults = { region = "eu-west-1" } }
+ mock_data "aws_caller_identity" { defaults = { account_id = "123456789012" } }
+ mock_data "aws_vpcs" { defaults = { ids = ["vpc-0123456789abcdef0"] } }
+ mock_resource "aws_sqs_queue" { defaults = { arn = "arn:aws:sqs:eu-west-1:123456789012:carlos-dev-fixed-terminations", id = "https://sqs.eu-west-1.amazonaws.com/123456789012/carlos-dev-fixed-terminations" } }
+
+ mock_resource "aws_launch_template" { defaults = { id = "lt-0123456789abcdef0" } }
+ mock_resource "aws_security_group" { defaults = { id = "sg-0123456789abcdef1" } }
+}
+override_data {
+ target = module.group.data.aws_region.current
+ values = { region = "eu-west-1" }
+}
+override_data {
+ target = module.group.data.aws_partition.current
+ values = { partition = "aws", dns_suffix = "amazonaws.com" }
+}
+override_data {
+ target = module.group.data.aws_caller_identity.current
+ values = { account_id = "123456789012" }
+}
+override_data {
+ target = module.group.data.aws_vpc.host
+ values = { cidr_block = "10.0.0.0/16", cidr_block_associations = [] }
+}
+override_data {
+ target = module.group.data.aws_subnets.group
+ values = { ids = ["subnet-00000000000000001", "subnet-00000000000000002"] }
+}
+override_data {
+ target = module.group.data.aws_route_table.group
+ values = { routes = [{ cidr_block = "0.0.0.0/0", gateway_id = "igw-0123456789abcdef0", carrier_gateway_id = "", core_network_arn = "", destination_prefix_list_id = "", egress_only_gateway_id = "", instance_id = "", ipv6_cidr_block = "", local_gateway_id = "", nat_gateway_id = "", network_interface_id = "", odb_network_arn = "", transit_gateway_id = "", vpc_endpoint_id = "", vpc_peering_connection_id = "" }] }
+}
+override_data {
+ target = module.group.data.aws_lb.group
+ values = {
+ vpc_id = "vpc-0123456789abcdef0"
+ internal = false
+ load_balancer_type = "network"
+ ip_address_type = "ipv4"
+ enable_cross_zone_load_balancing = true
+ security_groups = ["sg-0123456789abcdef0"]
+ subnet_mapping = [
+ { subnet_id = "subnet-00000000000000001", allocation_id = "eipalloc-00000000000000001", ipv6_address = "", outpost_id = "", private_ipv4_address = "" },
+ { subnet_id = "subnet-00000000000000002", allocation_id = "eipalloc-00000000000000002", ipv6_address = "", outpost_id = "", private_ipv4_address = "" }
+ ]
+ }
+}
+override_data {
+ target = module.group.data.aws_lb_target_group.group_http
+ values = { vpc_id = "vpc-0123456789abcdef0", port = 80, protocol = "TCP", target_type = "instance", load_balancer_arns = ["arn:aws:elasticloadbalancing:eu-west-1:123456789012:loadbalancer/net/test/1234"], preserve_client_ip = "true" }
+}
+override_data {
+ target = module.group.data.aws_lb_target_group.group_https
+ values = { vpc_id = "vpc-0123456789abcdef0", port = 443, protocol = "TCP", target_type = "instance", load_balancer_arns = ["arn:aws:elasticloadbalancing:eu-west-1:123456789012:loadbalancer/net/test/1234"], preserve_client_ip = "true" }
+}
+override_data {
+ target = module.group.data.aws_eip.group
+ values = { public_ip = "198.51.100.10" }
+}
+override_resource {
+ target = module.group.aws_sqs_queue.terminations
+ values = { arn = "arn:aws:sqs:eu-west-1:123456789012:carlos-dev-ie-group-terminations", id = "https://sqs.eu-west-1.amazonaws.com/123456789012/carlos-dev-ie-group-terminations" }
+}
+override_resource {
+ target = module.group.aws_cloudwatch_event_rule.terminations
+ values = { arn = "arn:aws:events:eu-west-1:123456789012:rule/carlos-dev-ie-group-terminations" }
+}
+override_resource {
+ target = module.group.aws_iam_role.host
+ values = { id = "carlos-dev-ie-group", arn = "arn:aws:iam::123456789012:role/carlos-dev-ie-group" }
+}
+
+run "fixed_and_group_are_distinct" {
+ command = plan
+ module { source = "./tests/fixed-and-group" }
+ assert {
+ condition = (
+ module.fixed.instance_id != null && module.group.instance_id == null &&
+ module.fixed.group_name == null && module.group.group_name == "carlos-dev-ie-group" &&
+ module.fixed.role_name == "carlos-dev-fixed" && module.group.role_name == "carlos-dev-ie-group" &&
+ module.fixed.termination_queue_url == "https://sqs.eu-west-1.amazonaws.com/123456789012/carlos-dev-fixed-terminations" &&
+ module.group.termination_queue_url == "https://sqs.eu-west-1.amazonaws.com/123456789012/carlos-dev-ie-group-terminations"
+ )
+ error_message = "fixed hosts and groups must have separate identities, roles and termination queues"
+ }
+}
+
+override_data {
+ target = module.group.data.aws_ami.group
+ values = { id = "ami-0123456789abcdef0", root_device_name = "/dev/xvda", root_device_type = "ebs" }
+}
diff --git a/infra/modules/region-host/tests/instance_metadata.tftest.hcl b/infra/modules/region-host/tests/instance_metadata.tftest.hcl
index a2c60aa2e..852fdb8a4 100644
--- a/infra/modules/region-host/tests/instance_metadata.tftest.hcl
+++ b/infra/modules/region-host/tests/instance_metadata.tftest.hcl
@@ -35,15 +35,15 @@ variables {
run "imdsv2_only" {
command = plan
assert {
- condition = aws_instance.host.metadata_options[0].http_tokens == "required"
+ condition = aws_instance.host[0].metadata_options[0].http_tokens == "required"
error_message = "the host requires IMDSv2 tokens"
}
assert {
- condition = aws_instance.host.metadata_options[0].http_put_response_hop_limit == 1
+ condition = aws_instance.host[0].metadata_options[0].http_put_response_hop_limit == 1
error_message = "the IMDS token must not leave the box (hop limit 1)"
}
assert {
- condition = aws_instance.host.metadata_options[0].http_endpoint == "enabled"
+ condition = aws_instance.host[0].metadata_options[0].http_endpoint == "enabled"
error_message = "the endpoint stays on: the box role is how the host reaches AWS"
}
}
diff --git a/infra/modules/region-host/variables.tf b/infra/modules/region-host/variables.tf
index 831ad99b5..c55985cfb 100644
--- a/infra/modules/region-host/variables.tf
+++ b/infra/modules/region-host/variables.tf
@@ -257,3 +257,111 @@ variable "console_mail_region" {
type = string
default = ""
}
+
+variable "mode" {
+ type = string
+ default = "fixed"
+ nullable = false
+ validation {
+ condition = contains(["fixed", "group"], var.mode)
+ error_message = "mode must be fixed or group"
+ }
+
+}
+
+variable "box_count" {
+ type = number
+ default = 1
+ nullable = false
+ validation {
+ condition = var.box_count >= 1 && floor(var.box_count) == var.box_count
+ error_message = "box_count must be a positive whole number"
+ }
+}
+
+variable "group_config" {
+ type = object({
+ deployment = string
+ region = string
+ placement_region = string
+ pools = set(string)
+ ami_id = string
+ release = string
+ configuration_kms_key_arn = string
+ })
+ default = null
+ validation {
+ condition = var.mode != "group" || var.group_config == null ? true : (
+ alltrue([for value in [var.group_config.deployment, var.group_config.region, var.group_config.placement_region] : can(regex("^[a-z][a-z0-9-]{0,31}$", value))]) &&
+ var.group_config.region != "shared" &&
+ length(var.group_config.pools) > 0 && alltrue([for pool in var.group_config.pools : can(regex("^[a-z][a-z0-9-]{0,31}$", pool))]) &&
+ can(regex("^ami-[0-9a-f]{17}$", var.group_config.ami_id)) &&
+ can(regex("^(v[0-9]+\\.[0-9]+\\.[0-9]+(-[a-zA-Z0-9.-]+)?|[0-9a-f]{64})$", var.group_config.release)) &&
+ can(regex("^arn:${data.aws_partition.current[0].partition}:kms:${data.aws_region.current.region}:${data.aws_caller_identity.current.account_id}:key/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", var.group_config.configuration_kms_key_arn)) &&
+ alltrue([for arn in [var.deployment_bucket_arn, var.data_bucket_arn] : can(regex("^arn:${data.aws_partition.current[0].partition}:s3:::[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$", arn))])
+ )
+ error_message = "group_config must name safe deployment, region and pool identifiers, a pinned AMI and release, regional configuration KMS key and bucket ARNs"
+ }
+}
+
+variable "group_zones" {
+ type = map(object({
+ subnet_id = string
+ allocation_id = string
+ }))
+ default = {}
+ nullable = false
+ validation {
+ condition = var.mode != "group" ? true : (
+ length(var.group_zones) >= 2 &&
+ length(distinct([for zone in var.group_zones : zone.subnet_id])) == length(var.group_zones) &&
+ alltrue([for az, zone in var.group_zones : can(regex("^${data.aws_region.current.region}[a-z]$", az)) && can(regex("^subnet-[0-9a-f]{17}$", zone.subnet_id))]) &&
+ alltrue([for zone in var.group_zones : zone.allocation_id == null ? true : can(regex("^eipalloc-[0-9a-f]{17}$", zone.allocation_id))]) &&
+ length(distinct(compact([for zone in var.group_zones : zone.allocation_id]))) == length([for zone in var.group_zones : zone if zone.allocation_id != null])
+ )
+ error_message = "group_zones needs at least two distinct public subnets in regional availability zones, with no reused EIP allocation"
+ }
+}
+
+variable "group_ingress" {
+ type = object({
+ nlb_arn = string
+ nlb_security_group_id = string
+ target_group_arns = map(string)
+ public_ips = map(string)
+ })
+ default = null
+ validation {
+ condition = var.mode != "group" || var.group_ingress == null ? true : (
+ toset(keys(var.group_ingress.target_group_arns)) == toset(["80", "443"]) &&
+ length(distinct(values(var.group_ingress.target_group_arns))) == 2 &&
+ toset(keys(var.group_ingress.public_ips)) == toset(keys(var.group_zones)) &&
+ alltrue([for ip in var.group_ingress.public_ips : can(cidrnetmask("${ip}/32"))]) &&
+ can(regex("^sg-[0-9a-f]{17}$", var.group_ingress.nlb_security_group_id)) &&
+ can(regex("^arn:${data.aws_partition.current[0].partition}:elasticloadbalancing:${data.aws_region.current.region}:${data.aws_caller_identity.current.account_id}:loadbalancer/net/[A-Za-z0-9/-]+$", var.group_ingress.nlb_arn)) &&
+ alltrue([for arn in var.group_ingress.target_group_arns : can(regex("^arn:${data.aws_partition.current[0].partition}:elasticloadbalancing:${data.aws_region.current.region}:${data.aws_caller_identity.current.account_id}:targetgroup/[A-Za-z0-9/-]+$", arn))])
+ )
+ error_message = "group_ingress must name this account and region's NLB, both target groups, its security group and one public IPv4 per group zone"
+ }
+}
+
+variable "group_launch_template_version" {
+ type = number
+ default = 1
+ nullable = false
+ validation {
+ condition = var.group_launch_template_version >= 1 && floor(var.group_launch_template_version) == var.group_launch_template_version
+ error_message = "group_launch_template_version must pin a positive numeric version"
+ }
+}
+
+variable "group_transaction_open" {
+ type = bool
+ default = false
+ nullable = false
+ description = "Set from the operator transaction record before planning. An open transaction refuses group changes."
+ validation {
+ condition = !var.group_transaction_open
+ error_message = "finish the open group maintenance transaction before planning or applying infrastructure"
+ }
+}
diff --git a/scripts/check-region-group-plan.py b/scripts/check-region-group-plan.py
index c375dccd5..418075748 100755
--- a/scripts/check-region-group-plan.py
+++ b/scripts/check-region-group-plan.py
@@ -303,6 +303,59 @@ def cleanup_entries(manifest, rows):
return disposable
+IDENTITY_FIELDS = {'instance_id', 'network_interface_id', 'role', 'allocation_id'}
+
+
+def unknown_identity_paths(value, path=()):
+ if isinstance(value, dict):
+ for key, child in value.items():
+ if key in IDENTITY_FIELDS and unknown(child):
+ yield path + (key,)
+ else:
+ yield from unknown_identity_paths(child, path + (key,))
+ elif isinstance(value, list):
+ for index, child in enumerate(value):
+ yield from unknown_identity_paths(child, path + (str(index),))
+
+
+def group_role_provenance(document, parsed, address, kind, change, paths, identities):
+ # This exception proves one destination: a newly created group's new role.
+ # Instance state, disks, ENIs and EIPs have no group-create exception.
+ if (kind not in {'aws_iam_role_policy', 'aws_iam_role_policy_attachment', 'aws_iam_instance_profile'} or
+ change['actions'] != ['create'] or paths != [('role',)]):
+ return False
+ parts = address_parts(address)
+ prefix = address[:parts.start('type')]
+ role_address = prefix + 'aws_iam_role.host'
+ roles = [c for a, k, n, c in parsed if a == role_address and k == 'aws_iam_role' and n == 'host']
+ groups = [c for a, k, n, c in parsed if a == prefix + 'aws_autoscaling_group.group[0]' and
+ k == 'aws_autoscaling_group' and n == 'group']
+ if len(roles) != 1 or len(groups) != 1:
+ return False
+ for candidate in [roles[0], groups[0]]:
+ name = (candidate['after'] or {}).get('name')
+ if (candidate['actions'] != ['create'] or not isinstance(name, str) or not name or
+ name in identities or unknown(candidate['after_unknown'].get('name', False))):
+ return False
+ # Configuration references must resolve inside this exact module instance.
+ # Indexed module calls cannot be proven from static configuration alone.
+ if '[' in prefix:
+ return False
+ module = document.get('configuration', {}).get('root_module', {})
+ for call in re.findall(r'module\.(' + IDENT + r')\.', prefix):
+ module = module.get('module_calls', {}).get(call, {}).get('module', {})
+ local_address = re.sub(r'\[[^\]]+\]$', '', address[len(prefix):])
+ configs = [r for r in module.get('resources', []) if r.get('address') == local_address]
+ if len(configs) != 1:
+ return False
+ expression = configs[0].get('expressions', {}).get('role', {})
+ if set(expression) != {'references'}:
+ return False
+ refs = expression['references']
+ return (isinstance(refs, list) and
+ set(refs) in [{'aws_iam_role.host.id'}, {'aws_iam_role.host.id', 'aws_iam_role.host'}])
+
+
def check(document, entries, manifest):
rows = changes(document)
parsed = [parse_resource(row) for row in rows]
@@ -335,6 +388,12 @@ def check(document, entries, manifest):
if row['mode'] == 'data':
continue
before, after, actions = change['before'], change['after'], change['actions']
+ if change['after_unknown'] is True:
+ raise Refused(UNKNOWN % address)
+ identity_paths = list(unknown_identity_paths(change['after_unknown']))
+ if identity_paths and not group_role_provenance(
+ document, parsed, address, kind, change, identity_paths, identities):
+ raise Refused(UNKNOWN % address)
# Adding a standalone rule also changes a fixed SG. Unknown destinations
# are refused; this module uses inline rules for its new NLB SG.
if kind in RULES and actions == ['create']:
diff --git a/scripts/check_region_group_plan_test.py b/scripts/check_region_group_plan_test.py
index 526d204a8..07313cd33 100644
--- a/scripts/check_region_group_plan_test.py
+++ b/scripts/check_region_group_plan_test.py
@@ -24,6 +24,57 @@ def plan(*resources):
class GateTests(unittest.TestCase):
+ def test_unknown_foreign_identity(self):
+ for kind, field in [('aws_ec2_instance_state', 'instance_id'),
+ ('aws_volume_attachment', 'instance_id'),
+ ('aws_network_interface_attachment', 'network_interface_id'),
+ ('aws_iam_role_policy', 'role'),
+ ('aws_eip_association', 'allocation_id')]:
+ with self.subTest(kind=kind):
+ document = self.fixture('fixed-identities.json')
+ document['resource_changes'] = [resource(
+ f'module.foreign.{kind}.ambiguous', kind, 'ambiguous',
+ after={}, actions=['create'], unknown={field: True})]
+ self.gate(document, 1)
+
+ def test_unknown_nested_identity_and_entire_shape(self):
+ for value in [True, {'network_interface': [{'network_interface_id': True}]},
+ {'connection': {'instance_id': True}}, {'connection': {'role': True}}]:
+ document = self.fixture('fixed-identities.json')
+ document['resource_changes'] = [resource('module.foreign.custom_resource.unknown',
+ 'custom_resource', 'unknown', after={}, actions=['create'], unknown=value)]
+ self.gate(document, 1)
+
+ def test_resolved_group_role_provenance(self):
+ role = resource('module.group.aws_iam_role.host', 'aws_iam_role', 'host',
+ after={'name': 'new-group-role'}, actions=['create'], unknown={'id': True})
+ group = resource('module.group.aws_autoscaling_group.group[0]', 'aws_autoscaling_group', 'group',
+ after={'name': 'new-group', 'min_size': 2, 'max_size': 2, 'desired_capacity': 2},
+ actions=['create'])
+ policy = resource('module.group.aws_iam_role_policy.group[0]', 'aws_iam_role_policy', 'group',
+ after={'policy': '{}'}, actions=['create'], unknown={'role': True})
+ document = plan(role, group, policy)
+ document['configuration'] = {'root_module': {'module_calls': {'group': {'module': {
+ 'resources': [
+ {'address': 'aws_iam_role.host', 'expressions': {'name': {'constant_value': 'new-group-role'}}},
+ {'address': 'aws_iam_role_policy.group', 'expressions': {'role': {'references': ['aws_iam_role.host.id', 'aws_iam_role.host']}}}
+ ]}}}}}
+ self.gate(document, 0)
+ for mutation in ['no-config', 'foreign-reference', 'existing-role', 'no-asg', 'unknown-name']:
+ bad = copy.deepcopy(document)
+ if mutation == 'no-config':
+ del bad['configuration']
+ elif mutation == 'foreign-reference':
+ bad['configuration']['root_module']['module_calls']['group']['module']['resources'][1]['expressions']['role']['references'] = ['module.fixed.aws_iam_role.host.id']
+ elif mutation == 'existing-role':
+ bad['resource_changes'][0]['change'].update(before={'name': 'new-group-role'}, actions=['no-op'], after_unknown={})
+ elif mutation == 'no-asg':
+ bad['resource_changes'].pop(1)
+ else:
+ bad['resource_changes'][0]['change']['after_unknown']['name'] = True
+ with self.subTest(mutation=mutation):
+ self.gate(bad, 1)
+
def fixture(self, name):
return json.loads((GATE.parent / 'testdata/region-group-plan' / name).read_text())
diff --git a/scripts/region_group_contract_test.py b/scripts/region_group_contract_test.py
new file mode 100644
index 000000000..d1b10a8e5
--- /dev/null
+++ b/scripts/region_group_contract_test.py
@@ -0,0 +1,242 @@
+"""Audit complete mock plans from tofu test -json -verbose.
+
+Pass region-host's event file. The fixed snapshot was generated from the
+Task 2 base commit using fixed_state_unchanged, with the same mock region.
+"""
+import base64
+import fnmatch
+import json
+from pathlib import Path
+import subprocess
+import sys
+
+
+def seq(value):
+ return value if isinstance(value, list) else [value]
+
+
+def matches(value, patterns):
+ return any(fnmatch.fnmatchcase(value, p) for p in seq(patterns))
+
+
+def allowed(statements, action, resource, context=None):
+ context = context or {}
+ verdict = False
+ for s in statements:
+ if not matches(action, s['Action']):
+ continue
+ if 'Resource' in s and not matches(resource, s['Resource']):
+ continue
+ if 'NotResource' in s and matches(resource, s['NotResource']):
+ continue
+ conditions = []
+ for op, pairs in s.get('Condition', {}).items():
+ assert op in {'StringEquals', 'StringLike', 'ArnEquals', 'ArnNotEquals',
+ 'ForAllValues:StringEquals', 'ForAllValues:StringLike'}, op
+ for key, expected in pairs.items():
+ actual = seq(context[key]) if key in context else []
+ match = matches if op.endswith('Like') or op.startswith('Arn') else lambda a, b: a in seq(b)
+ result = bool(actual) and all(match(a, expected) for a in actual)
+ conditions.append(not result if op == 'ArnNotEquals' else result)
+ if not all(conditions):
+ continue
+ if s['Effect'] == 'Deny':
+ return False
+ verdict = True
+ return verdict
+
+
+# AmazonSSMManagedInstanceCore v2, checked against AWS's managed-policy
+# reference on 2026-11-04. Its wildcard parameter reads participate in every
+# negative test below; inline Allows alone cannot establish these boundaries.
+SSM_CORE = {
+ 'ssm:DescribeAssociation', 'ssm:GetDeployablePatchSnapshotForInstance',
+ 'ssm:GetDocument', 'ssm:DescribeDocument', 'ssm:GetManifest',
+ 'ssm:GetParameter', 'ssm:GetParameters', 'ssm:ListAssociations',
+ 'ssm:ListInstanceAssociations', 'ssm:PutInventory', 'ssm:PutComplianceItems',
+ 'ssm:PutConfigurePackageResult', 'ssm:UpdateAssociationStatus',
+ 'ssm:UpdateInstanceAssociationStatus', 'ssm:UpdateInstanceInformation',
+ 'ssmmessages:CreateControlChannel', 'ssmmessages:CreateDataChannel',
+ 'ssmmessages:OpenControlChannel', 'ssmmessages:OpenDataChannel',
+ 'ec2messages:AcknowledgeMessage', 'ec2messages:DeleteMessage',
+ 'ec2messages:FailMessage', 'ec2messages:GetEndpoint',
+ 'ec2messages:GetMessages', 'ec2messages:SendReply',
+}
+
+
+def audit_group(plan, dns):
+ rows = plan['planned_values']['root_module']['resources']
+ resources = {r['address']: r['values'] for r in rows if r['mode'] == 'managed'}
+ policies = {r['name']: json.loads(r['values']['policy'])['Statement'] for r in rows
+ if r['type'] == 'aws_iam_role_policy'}
+ expected = {'group', 'host_buckets', 'host_metrics', 'host_terminations',
+ 'host_ssm_parameter_scope', 'host_release_key_deny'}
+ if dns:
+ expected |= {'host_route53', 'host_steering'}
+ assert set(policies) == expected, set(policies)
+ attachments = [r['values'] for r in rows if r['type'] == 'aws_iam_role_policy_attachment']
+ assert len(attachments) == 1
+ assert attachments[0]['policy_arn'] == 'arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore'
+ assert attachments[0]['role'] == 'carlos-dev-ie-group'
+ assert not any(r['type'] in {'aws_iam_policy', 'aws_iam_policy_attachment'} for r in rows)
+ for r in rows:
+ if r['type'] == 'aws_iam_role_policy':
+ assert r['values']['role'] == 'carlos-dev-ie-group'
+ statements = [s for policy in policies.values() for s in policy]
+ statements.append({'Effect': 'Allow', 'Action': sorted(SSM_CORE), 'Resource': '*'})
+ actions = {a for s in statements if s['Effect'] == 'Allow' for a in seq(s['Action'])}
+ expected_actions = SSM_CORE | {
+ 'ssm:GetParameterHistory', 'ssm:GetParametersByPath', 'kms:Decrypt',
+ 'autoscaling:CompleteLifecycleAction', 'ec2:DescribeInstances',
+ 's3:GetObject', 's3:PutObject', 's3:DeleteObject', 's3:GetObjectVersion',
+ 's3:ListBucket', 's3:GetBucketLocation', 's3:DeleteObjectVersion',
+ 's3:ListBucketVersions', 'cloudwatch:PutMetricData',
+ 'sqs:ReceiveMessage', 'sqs:DeleteMessage', 'sqs:GetQueueAttributes',
+ }
+ if dns:
+ expected_actions |= {'route53:ChangeResourceRecordSets', 'route53:GetChange',
+ 'route53:ListHostedZonesByName', 'route53:ListResourceRecordSets',
+ 'route53:ListHealthChecks', 'route53:CreateHealthCheck',
+ 'route53:DeleteHealthCheck', 'route53:ChangeTagsForResource',
+ 'route53:ListTagsForResources'}
+ assert actions == expected_actions, actions ^ expected_actions
+ expected_pairs = {(a, '*') for a in SSM_CORE}
+ parameter_resources = ['arn:aws:ssm:eu-west-1:123456789012:parameter/carlos/dev/' + p
+ for p in ['ie', 'ie/*', 'shared', 'shared/*']]
+ groups = [
+ (['ssm:GetParameter', 'ssm:GetParameters', 'ssm:GetParameterHistory', 'ssm:GetParametersByPath'], parameter_resources),
+ (['kms:Decrypt'], ['arn:aws:kms:eu-west-1:123456789012:key/00000000-0000-0000-0000-000000000001']),
+ (['autoscaling:CompleteLifecycleAction'], ['arn:aws:autoscaling:eu-west-1:123456789012:autoScalingGroup:*:autoScalingGroupName/carlos-dev-ie-group']),
+ (['ec2:DescribeInstances', 'cloudwatch:PutMetricData'], ['*']),
+ (['sqs:ReceiveMessage', 'sqs:DeleteMessage', 'sqs:GetQueueAttributes'], ['arn:aws:sqs:eu-west-1:123456789012:carlos-dev-ie-group-terminations']),
+ (['s3:GetObject', 's3:PutObject', 's3:DeleteObject', 's3:GetObjectVersion'], ['arn:aws:s3:::carlos-dev-platform/*', 'arn:aws:s3:::carlos-dev-ie/*']),
+ (['s3:ListBucket', 's3:GetBucketLocation'], ['arn:aws:s3:::carlos-dev-platform', 'arn:aws:s3:::carlos-dev-ie']),
+ (['s3:DeleteObjectVersion'], ['arn:aws:s3:::carlos-dev-ie/' + p for p in ['instances/*', 'moves/*', 'move-snapshots/*']]),
+ (['s3:ListBucketVersions'], ['arn:aws:s3:::carlos-dev-ie']),
+ ]
+ if dns:
+ groups += [
+ (['route53:ChangeResourceRecordSets'], ['arn:aws:route53:::hostedzone/ZTESTDNS', 'arn:aws:route53:::hostedzone/ZTESTSTEERING']),
+ (['route53:GetChange'], ['arn:aws:route53:::change/*']),
+ (['route53:ListResourceRecordSets'], ['arn:aws:route53:::hostedzone/ZTESTSTEERING']),
+ (['route53:ListHostedZonesByName', 'route53:ListHealthChecks', 'route53:CreateHealthCheck'], ['*']),
+ (['route53:DeleteHealthCheck', 'route53:ChangeTagsForResource', 'route53:ListTagsForResources'], ['arn:aws:route53:::healthcheck/*']),
+ ]
+ expected_pairs |= {(a, r) for acts, targets in groups for a in acts for r in targets}
+ pairs = {(a, r) for s in statements if s['Effect'] == 'Allow' for a in seq(s['Action']) for r in seq(s['Resource'])}
+ assert pairs == expected_pairs, pairs ^ expected_pairs
+ assert allowed(statements, 'cloudwatch:PutMetricData', '*', {'cloudwatch:namespace': 'Carlos/Host'})
+ assert not allowed(statements, 'cloudwatch:PutMetricData', '*', {'cloudwatch:namespace': 'Other'})
+ parameter = 'arn:aws:ssm:eu-west-1:123456789012:parameter'
+ for prefix in ['/carlos/dev/ie', '/carlos/dev/shared']:
+ for suffix in ['', '/ENV', '/boot/bootstrap-object', '/boot/bootstrap-sha256', '/boot/ingress']:
+ for action in ['ssm:GetParameter', 'ssm:GetParameters', 'ssm:GetParameterHistory', 'ssm:GetParametersByPath']:
+ assert allowed(statements, action, parameter + prefix + suffix)
+ for path in ['', '/', '/carlos', '/carlos/', '/carlos/dev', '/carlos/dev/',
+ '/carlos/release-key', '/carlos/dev/fr/key', '/carlos/dev/ie-other/key',
+ '/carlos/other/ie/key', '/carlos/dev/shared-other/key']:
+ for action in ['ssm:GetParameter', 'ssm:GetParameters', 'ssm:GetParametersByPath', 'ssm:GetParameterHistory']:
+ assert not allowed(statements, action, parameter + path), (action, path)
+ assert not allowed(statements, 'ssm:GetParameter', parameter.replace('eu-west-1', 'eu-west-2') + '/carlos/dev/ie/key')
+ assert not allowed(statements, 'ssm:PutParameter', parameter + '/carlos/dev/ie/ENV')
+ key = 'arn:aws:kms:eu-west-1:123456789012:key/00000000-0000-0000-0000-000000000001'
+ ctx = {'kms:ViaService': 'ssm.eu-west-1.amazonaws.com', 'kms:EncryptionContext:PARAMETER_ARN': parameter + '/carlos/dev/ie/ENV'}
+ assert allowed(statements, 'kms:Decrypt', key, ctx)
+ assert not allowed(statements, 'kms:Decrypt', key)
+ assert not allowed(statements, 'kms:Decrypt', key[:-1] + '2', ctx)
+ for name, value in [('kms:ViaService', 'ssm.eu-west-2.amazonaws.com'),
+ ('kms:EncryptionContext:PARAMETER_ARN', parameter + '/carlos/dev/fr/ENV')]:
+ assert not allowed(statements, 'kms:Decrypt', key, dict(ctx, **{name: value}))
+ group = 'arn:aws:autoscaling:eu-west-1:123456789012:autoScalingGroup:uuid:autoScalingGroupName/carlos-dev-ie-group'
+ tags = {'aws:ResourceTag/carlos:deployment': 'dev', 'aws:ResourceTag/carlos:region': 'ie'}
+ assert allowed(statements, 'autoscaling:CompleteLifecycleAction', group, tags)
+ for wrong in [group + '-other', group.replace('123456789012', '999999999999'), group.replace('eu-west-1', 'eu-west-2')]:
+ assert not allowed(statements, 'autoscaling:CompleteLifecycleAction', wrong, tags)
+ assert not allowed(statements, 'autoscaling:CompleteLifecycleAction', group)
+ assert not allowed(statements, 'autoscaling:CompleteLifecycleAction', group, dict(tags, **{'aws:ResourceTag/carlos:region': 'fr'}))
+ for action in ['autoscaling:UpdateAutoScalingGroup', 'autoscaling:EnterStandby', 'autoscaling:ExitStandby',
+ 'autoscaling:RecordLifecycleActionHeartbeat', 'autoscaling:SetInstanceHealth',
+ 'elasticloadbalancing:RegisterTargets', 'ec2:TerminateInstances', 'iam:CreateUser']:
+ assert not allowed(statements, action, '*', tags)
+ assert allowed(statements, 'ec2:DescribeInstances', '*', {'aws:RequestedRegion': 'eu-west-1'})
+ assert not allowed(statements, 'ec2:DescribeInstances', '*', {'aws:RequestedRegion': 'eu-west-2'})
+ assert not allowed(statements, 'ec2:DescribeInstances', '*')
+ bucket = 'arn:aws:s3:::carlos-dev-platform'
+ for path in ['control/box-roles/i-test.json', 'control/box-roles/default/ie.json']:
+ assert allowed(statements, 's3:GetObject', bucket + '/' + path)
+ for action in ['s3:PutObject', 's3:DeleteObject', 's3:DeleteObjectVersion', 's3:PutObjectTagging',
+ 's3:DeleteObjectTagging', 's3:PutObjectVersionTagging', 's3:DeleteObjectVersionTagging']:
+ assert not allowed(statements, action, bucket + '/' + path)
+ for path in ['control/edges/i-test.json', 'control/identities/i-test.json', 'control/terminations/i-test.json']:
+ assert allowed(statements, 's3:PutObject', bucket + '/' + path)
+ data = 'arn:aws:s3:::carlos-dev-ie'
+ assert allowed(statements, 's3:DeleteObject', data + '/instances/shop/lock.json')
+ for path in ['moves/_lane/probe', 'move-snapshots/shop/op/db', 'instances/shop/build-state.json']:
+ assert allowed(statements, 's3:DeleteObjectVersion', data + '/' + path)
+ assert allowed(statements, 's3:ListBucketVersions', data, {'s3:prefix': path})
+ assert not allowed(statements, 's3:DeleteObjectVersion', bucket + '/' + path)
+ for path in ['', 'control/', 'moves-other/', 'private/']:
+ assert not allowed(statements, 's3:ListBucketVersions', data, {'s3:prefix': path})
+ assert not allowed(statements, 's3:DeleteObjectVersion', data + '/' + path)
+ assert not allowed(statements, 's3:ListBucketVersions', data)
+ queue = resources['aws_sqs_queue.terminations']
+ arn = 'arn:aws:sqs:eu-west-1:123456789012:carlos-dev-ie-group-terminations'
+ assert queue['arn'] == arn
+ assert queue['id'] == 'https://sqs.eu-west-1.amazonaws.com/123456789012/carlos-dev-ie-group-terminations'
+ for action in ['sqs:ReceiveMessage', 'sqs:DeleteMessage', 'sqs:GetQueueAttributes']:
+ assert allowed(statements, action, arn)
+ for other in [arn.replace('-group-', '-fixed-'), arn.replace('eu-west-1', 'eu-west-2'), arn.replace('123456789012', '999999999999')]:
+ assert not allowed(statements, action, other)
+ for action in ['sqs:SendMessage', 'sqs:ChangeMessageVisibility', 'sqs:GetQueueUrl']:
+ assert not allowed(statements, action, arn)
+ queue_policy = json.loads(resources['aws_sqs_queue_policy.terminations']['policy'])['Statement']
+ # Include an identity Allow to prove the resource Deny beats forged sends.
+ queue_policy += [{'Effect': 'Allow', 'Action': 'sqs:SendMessage', 'Resource': '*'}]
+ rule = resources['aws_cloudwatch_event_rule.terminations']['arn']
+ assert allowed(queue_policy, 'sqs:SendMessage', arn, {'aws:SourceArn': rule})
+ assert not allowed(queue_policy, 'sqs:SendMessage', arn)
+ assert not allowed(queue_policy, 'sqs:SendMessage', arn, {'aws:SourceArn': rule + '-forged'})
+ if dns:
+ ctx = {'route53:ChangeResourceRecordSetsRecordTypes': ['TXT'], 'route53:ChangeResourceRecordSetsActions': ['UPSERT'],
+ 'route53:ChangeResourceRecordSetsNormalizedRecordNames': ['_acme-challenge.example.com']}
+ assert allowed(statements, 'route53:ChangeResourceRecordSets', 'arn:aws:route53:::hostedzone/ZTESTDNS', ctx)
+ assert not allowed(statements, 'route53:ChangeResourceRecordSets', 'arn:aws:route53:::hostedzone/ZFOREIGN', ctx)
+ assert not allowed(statements, 'route53:ChangeResourceRecordSets', 'arn:aws:route53:::hostedzone/ZTESTDNS', dict(ctx, **{'route53:ChangeResourceRecordSetsRecordTypes': ['A']}))
+ script = base64.b64decode(resources['aws_launch_template.group[0]']['user_data']).decode()
+ subprocess.run(['sh', '-n'], input=script, text=True, check=True)
+ assert 'CARLOS_BOOTSTRAP_OBJECT_KEY=\'/carlos/dev/ie/boot/bootstrap-object\'' in script
+ assert 'CARLOS_TERMINATION_QUEUE_URL=\'' + queue['id'] + "'" in script
+ assert script.rstrip().endswith('exit 1'), 'Task 3 must replace the fail-closed placeholder'
+ print('group combined policies, managed inheritance, denial witnesses and boot shell passed')
+
+
+def main(path):
+ seen = set()
+ for line in Path(path).read_text().splitlines():
+ event = json.loads(line)
+ plan = event.get('test_plan')
+ run = event.get('@testrun')
+ if plan is None:
+ continue
+ if run == 'fixed_state_unchanged':
+ actual = {r['address'].replace('[0]', ''): r['change']['after'] for r in plan['resource_changes'] if r['mode'] == 'managed'}
+ expected = json.loads((Path(__file__).parent / 'testdata/region-group-plan/fixed-resource-contract.json').read_text())
+ assert actual == expected, 'fixed resource attributes changed from Task 2 base'
+ print('fixed_state_unchanged: every managed resource attribute matches the original plan')
+ seen.add(run)
+ elif run == 'group_boot_quotes':
+ resources = {r['address']: r['values'] for r in plan['planned_values']['root_module']['resources']}
+ script = base64.b64decode(resources['aws_launch_template.group[0]']['user_data']).decode()
+ script = script.replace('\nexit 1', '\nprintf \'%s\' "$CARLOS_TERMINATION_QUEUE_URL"')
+ result = subprocess.run(['sh'], input=script, text=True, capture_output=True, check=True)
+ assert result.stdout == resources['aws_sqs_queue.terminations']['id'], result.stdout
+ print('group boot values remain literal under shell quote and command substitution probes')
+ seen.add(run)
+ elif run in {'group_iam_exact_scope', 'group_dns_duties_enabled'}:
+ audit_group(plan, run == 'group_dns_duties_enabled')
+ seen.add(run)
+ assert seen == {'fixed_state_unchanged', 'group_iam_exact_scope', 'group_dns_duties_enabled', 'group_boot_quotes'}, seen
+
+
+if __name__ == '__main__':
+ main(sys.argv[1])
diff --git a/scripts/testdata/region-group-plan/fixed-resource-contract.json b/scripts/testdata/region-group-plan/fixed-resource-contract.json
new file mode 100644
index 000000000..189411ec1
--- /dev/null
+++ b/scripts/testdata/region-group-plan/fixed-resource-contract.json
@@ -0,0 +1,359 @@
+{
+ "aws_cloudwatch_event_rule.terminations": {
+ "arn": "WEGGIHanLazS",
+ "description": "EC2 instances reaching terminated, for region HA failover.",
+ "event_bus_name": null,
+ "event_pattern": "{\"detail\":{\"state\":[\"terminated\"]},\"detail-type\":[\"EC2 Instance State-change Notification\"],\"source\":[\"aws.ec2\"]}",
+ "force_destroy": null,
+ "id": "XDJXsHYp0",
+ "is_enabled": null,
+ "name": "carlos-test-host-terminations",
+ "name_prefix": "HaZZC",
+ "region": "d3lpDlgNjx",
+ "role_arn": null,
+ "schedule_expression": null,
+ "state": null,
+ "tags": null,
+ "tags_all": {}
+ },
+ "aws_cloudwatch_event_target.terminations": {
+ "appsync_target": [],
+ "arn": "arn:aws:sqs:eu-west-1:123456789012:carlos-test-host-terminations",
+ "batch_target": [],
+ "dead_letter_config": [],
+ "ecs_target": [],
+ "event_bus_name": null,
+ "force_destroy": null,
+ "http_target": [],
+ "id": "OW3Lnom",
+ "input": null,
+ "input_path": null,
+ "input_transformer": [],
+ "kinesis_target": [],
+ "redshift_target": [],
+ "region": "FyIHV",
+ "retry_policy": [],
+ "role_arn": null,
+ "rule": "carlos-test-host-terminations",
+ "run_command_targets": [],
+ "sagemaker_pipeline_target": [],
+ "sqs_target": [],
+ "target_id": "94074w0jY3O"
+ },
+ "aws_cloudwatch_metric_alarm.host_auto_recover": {
+ "actions_enabled": null,
+ "alarm_actions": [
+ "arn:aws:automate:eu-west-1:ec2:recover"
+ ],
+ "alarm_description": "EC2 system-status-check failure \u2014 auto-recovers carlos-test-ie onto healthy hardware.",
+ "alarm_name": "carlos-test-ie-auto-recover",
+ "arn": "4v8aqy8ZV",
+ "comparison_operator": "GreaterThanOrEqualToThreshold",
+ "datapoints_to_alarm": null,
+ "dimensions": {
+ "InstanceId": "i-0123456789abcdef0"
+ },
+ "evaluate_low_sample_count_percentiles": "ftpmcCTESL",
+ "evaluation_criteria": [],
+ "evaluation_interval": null,
+ "evaluation_periods": 2,
+ "evaluation_window": [],
+ "extended_statistic": null,
+ "id": "rww11J47ygB",
+ "insufficient_data_actions": null,
+ "metric_name": "StatusCheckFailed_System",
+ "metric_query": [],
+ "namespace": "AWS/EC2",
+ "ok_actions": null,
+ "period": 60,
+ "region": "4M6nOqZL",
+ "statistic": "Maximum",
+ "tags": {
+ "Name": "carlos-test-ie-auto-recover"
+ },
+ "tags_all": {},
+ "threshold": 1,
+ "threshold_metric_id": null,
+ "treat_missing_data": null,
+ "unit": null,
+ "warm_up_configuration": []
+ },
+ "aws_eip.host": {
+ "address": null,
+ "allocation_id": "nOUuJ",
+ "arn": "abii7LIyl65j",
+ "associate_with_private_ip": null,
+ "association_id": "RfvafTGLnBTDEv",
+ "carrier_ip": "Yu6rVACOx3se9sU",
+ "customer_owned_ip": "k9Cjo",
+ "customer_owned_ipv4_pool": null,
+ "domain": "vpc",
+ "id": "yAJOM3ndzUuE",
+ "instance": "i-0123456789abcdef0",
+ "ipam_pool_id": "N8Rran3kPK",
+ "network_border_group": "is3K7CMG",
+ "network_interface": "9TpmPVrdFUl1C",
+ "private_dns": "tmXXsHTJBo",
+ "private_ip": "L6riU",
+ "ptr_record": "pAZP789aUdcjI",
+ "public_dns": "rvQBzq2sF8RC",
+ "public_ip": "192.0.2.10",
+ "public_ipv4_pool": "XyQm5fxU",
+ "region": "5cwAZKIsnXB",
+ "tags": {
+ "Name": "carlos-test-ie"
+ },
+ "tags_all": {},
+ "timeouts": null
+ },
+ "aws_iam_instance_profile.host": {
+ "arn": "sSC3ejlvnD8e3j",
+ "create_date": "Hr4Sn2DBgiyX",
+ "id": "rBLR68FfLgB1SS",
+ "name": "carlos-test-host",
+ "name_prefix": "gVrAOLquF6RL",
+ "path": null,
+ "role": "carlos-test-host",
+ "tags": null,
+ "tags_all": {},
+ "unique_id": "HoxheCJjbLns"
+ },
+ "aws_iam_role.host": {
+ "arn": "arn:aws:iam::123456789012:role/carlos-test-host",
+ "assume_role_policy": "{\"Statement\":[{\"Action\":\"sts:AssumeRole\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"ec2.amazonaws.com\"}}],\"Version\":\"2012-10-17\"}",
+ "create_date": "zBCL1RRid0rp0Gq",
+ "description": null,
+ "force_detach_policies": null,
+ "id": "MD610hxEDrXKow",
+ "inline_policy": [],
+ "managed_policy_arns": [],
+ "max_session_duration": null,
+ "name": "carlos-test-host",
+ "name_prefix": "MQDM",
+ "path": null,
+ "permissions_boundary": null,
+ "tags": null,
+ "tags_all": {},
+ "unique_id": "xf7ioXyMj"
+ },
+ "aws_iam_role_policy.host_buckets": {
+ "id": "PnS1QNTP",
+ "name": "carlos-test-host-buckets",
+ "name_prefix": "ngjHmua9AqfQM",
+ "policy": "{\"Statement\":[{\"Action\":[\"s3:GetObject\",\"s3:PutObject\",\"s3:DeleteObject\"],\"Effect\":\"Allow\",\"Resource\":[\"arn:aws:s3:::carlos-test-platform/*\",\"arn:aws:s3:::carlos-test-ie/*\"]},{\"Action\":[\"s3:ListBucket\",\"s3:GetBucketLocation\"],\"Effect\":\"Allow\",\"Resource\":[\"arn:aws:s3:::carlos-test-platform\",\"arn:aws:s3:::carlos-test-ie\"]},{\"Action\":[\"s3:GetObjectVersion\"],\"Effect\":\"Allow\",\"Resource\":[\"arn:aws:s3:::carlos-test-ie/*\"],\"Sid\":\"PullDoorObjectVersions\"},{\"Action\":[\"s3:DeleteObjectVersion\"],\"Effect\":\"Allow\",\"Resource\":[\"arn:aws:s3:::carlos-test-ie/*\"]},{\"Action\":[\"s3:ListBucketVersions\"],\"Effect\":\"Allow\",\"Resource\":[\"arn:aws:s3:::carlos-test-ie\"],\"Sid\":\"PullDoorVersionList\"},{\"Action\":[\"ssm:GetParameter\"],\"Effect\":\"Allow\",\"Resource\":\"arn:aws:ssm:eu-west-1:123456789012:parameter/carlos/*\"},{\"Action\":[\"ec2:DescribeInstances\",\"ec2:DescribeVolumes\",\"ec2:DescribeAddresses\",\"ec2:DescribeSecurityGroups\",\"ec2:DescribeVpcs\",\"ec2:DescribeSubnets\",\"ec2:DescribeRegions\",\"tag:GetResources\",\"s3:ListAllMyBuckets\",\"s3:GetBucketLocation\",\"s3:GetBucketVersioning\",\"s3:GetEncryptionConfiguration\",\"s3:GetBucketPublicAccessBlock\",\"route53:ListHostedZones\",\"route53:ListResourceRecordSets\",\"iam:ListRoles\",\"iam:ListUsers\",\"iam:ListAttachedRolePolicies\",\"cloudwatch:DescribeAlarms\",\"acm:ListCertificates\",\"sts:GetCallerIdentity\"],\"Effect\":\"Allow\",\"Resource\":\"*\"}],\"Version\":\"2012-10-17\"}",
+ "role": "MD610hxEDrXKow"
+ },
+ "aws_iam_role_policy.host_metrics": {
+ "id": "PnS1QNTP",
+ "name": "carlos-test-host-metrics",
+ "name_prefix": "ngjHmua9AqfQM",
+ "policy": "{\"Statement\":[{\"Action\":[\"cloudwatch:PutMetricData\"],\"Condition\":{\"StringEquals\":{\"cloudwatch:namespace\":\"Carlos/Host\"}},\"Effect\":\"Allow\",\"Resource\":\"*\"}],\"Version\":\"2012-10-17\"}",
+ "role": "MD610hxEDrXKow"
+ },
+ "aws_iam_role_policy.host_release_key_deny": {
+ "id": "PnS1QNTP",
+ "name": "carlos-test-host-release-key-deny",
+ "name_prefix": "ngjHmua9AqfQM",
+ "policy": "{\"Statement\":[{\"Action\":[\"ssm:GetParameter\",\"ssm:GetParameters\",\"ssm:GetParameterHistory\"],\"Effect\":\"Deny\",\"Resource\":\"arn:aws:ssm:*:123456789012:parameter/carlos/release-key\",\"Sid\":\"DenyReleaseKeyReads\"},{\"Action\":\"ssm:GetParametersByPath\",\"Effect\":\"Deny\",\"Resource\":[\"arn:aws:ssm:*:123456789012:parameter/carlos\",\"arn:aws:ssm:*:123456789012:parameter/carlos/\",\"arn:aws:ssm:*:123456789012:parameter\",\"arn:aws:ssm:*:123456789012:parameter/\"],\"Sid\":\"DenyReleaseKeyAncestorPathReads\"}],\"Version\":\"2012-10-17\"}",
+ "role": "MD610hxEDrXKow"
+ },
+ "aws_iam_role_policy.host_ssm_parameter_scope": {
+ "id": "PnS1QNTP",
+ "name": "carlos-test-host-ssm-parameter-scope",
+ "name_prefix": "ngjHmua9AqfQM",
+ "policy": "{\"Statement\":[{\"Action\":[\"ssm:GetParameter\",\"ssm:GetParameters\",\"ssm:GetParameterHistory\",\"ssm:GetParametersByPath\"],\"Effect\":\"Deny\",\"NotResource\":[\"arn:aws:ssm:eu-west-1:123456789012:parameter/carlos/*\"]}],\"Version\":\"2012-10-17\"}",
+ "role": "MD610hxEDrXKow"
+ },
+ "aws_iam_role_policy.host_terminations": {
+ "id": "PnS1QNTP",
+ "name": "carlos-test-host-terminations",
+ "name_prefix": "ngjHmua9AqfQM",
+ "policy": "{\"Statement\":[{\"Action\":[\"sqs:ReceiveMessage\",\"sqs:DeleteMessage\",\"sqs:GetQueueAttributes\"],\"Effect\":\"Allow\",\"Resource\":\"arn:aws:sqs:eu-west-1:123456789012:carlos-test-host-terminations\"}],\"Version\":\"2012-10-17\"}",
+ "role": "MD610hxEDrXKow"
+ },
+ "aws_iam_role_policy_attachment.host_ssm": {
+ "id": "THipllTx5U9G",
+ "policy_arn": "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore",
+ "role": "carlos-test-host"
+ },
+ "aws_instance.host": {
+ "ami": "ami-0123456789abcdef0",
+ "arn": "QwnkgeH",
+ "associate_public_ip_address": false,
+ "availability_zone": "eFkNnqw",
+ "capacity_reservation_specification": [],
+ "cpu_options": [],
+ "credit_specification": [],
+ "disable_api_stop": false,
+ "disable_api_termination": false,
+ "ebs_block_device": [],
+ "ebs_optimized": false,
+ "enable_primary_ipv6": false,
+ "enclave_options": [],
+ "ephemeral_block_device": [],
+ "force_destroy": null,
+ "get_password_data": null,
+ "hibernation": null,
+ "host_id": "JSPSTcOg3QOiv",
+ "host_resource_group_arn": "A6FF",
+ "iam_instance_profile": "carlos-test-host",
+ "id": "i-0123456789abcdef0",
+ "instance_initiated_shutdown_behavior": "mwcuHrS",
+ "instance_lifecycle": "syKC",
+ "instance_market_options": [],
+ "instance_state": "Q9BqhFH6RSIqvGH",
+ "instance_type": "t4g.small",
+ "ipv6_address_count": 0,
+ "ipv6_addresses": [],
+ "key_name": "YlBwEAX",
+ "launch_template": [],
+ "maintenance_options": [],
+ "metadata_options": [
+ {
+ "http_endpoint": "enabled",
+ "http_protocol_ipv6": null,
+ "http_put_response_hop_limit": 1,
+ "http_tokens": "required",
+ "instance_metadata_tags": "BGwGs4xl5gbB"
+ }
+ ],
+ "monitoring": false,
+ "network_interface": [],
+ "outpost_arn": "Wb0Vk",
+ "password_data": "skqDhjd2X7",
+ "placement_group": "B6rY",
+ "placement_group_id": "S7DOaz0XTZZ6",
+ "placement_partition_number": 0,
+ "primary_network_interface": [],
+ "primary_network_interface_id": "uxLze3oyIQ",
+ "private_dns": "8mdHutqKr",
+ "private_dns_name_options": [],
+ "private_ip": "bLsk26hUp8",
+ "public_dns": "IKPTmxp19S",
+ "public_ip": "GXmKGJ",
+ "region": "xflnJYQeQbIG61",
+ "root_block_device": [
+ {
+ "delete_on_termination": true,
+ "device_name": "KU2cgzzfJFhzfZm",
+ "encrypted": true,
+ "iops": 0,
+ "kms_key_id": "AhPsFbShB1K",
+ "tags": null,
+ "tags_all": {},
+ "throughput": 0,
+ "volume_id": "HJ6m2XIlsBE",
+ "volume_size": 20,
+ "volume_type": "gp3"
+ }
+ ],
+ "secondary_network_interface": [],
+ "secondary_private_ips": [],
+ "security_groups": [],
+ "source_dest_check": null,
+ "spot_instance_request_id": "L8wevOpwalE",
+ "subnet_id": "sOX9QI9kr",
+ "tags": {
+ "Name": "carlos-test-ie"
+ },
+ "tags_all": {},
+ "tenancy": "AFTgoZg",
+ "timeouts": null,
+ "user_data": "#!/bin/sh\n",
+ "user_data_base64": "nZRpp5LdRT",
+ "user_data_replace_on_change": false,
+ "volume_tags": null,
+ "vpc_security_group_ids": [
+ "sg-0123456789abcdef0"
+ ]
+ },
+ "aws_security_group.host": {
+ "arn": "UuxOvk",
+ "description": "carlos test host",
+ "egress": [
+ {
+ "cidr_blocks": [
+ "0.0.0.0/0"
+ ],
+ "description": null,
+ "from_port": 0,
+ "ipv6_cidr_blocks": null,
+ "prefix_list_ids": null,
+ "protocol": "-1",
+ "security_groups": null,
+ "self": null,
+ "to_port": 0
+ }
+ ],
+ "id": "sg-0123456789abcdef0",
+ "ingress": [
+ {
+ "cidr_blocks": [
+ "0.0.0.0/0"
+ ],
+ "description": null,
+ "from_port": 443,
+ "ipv6_cidr_blocks": null,
+ "prefix_list_ids": null,
+ "protocol": "tcp",
+ "security_groups": null,
+ "self": null,
+ "to_port": 443
+ },
+ {
+ "cidr_blocks": [
+ "0.0.0.0/0"
+ ],
+ "description": null,
+ "from_port": 80,
+ "ipv6_cidr_blocks": null,
+ "prefix_list_ids": null,
+ "protocol": "tcp",
+ "security_groups": null,
+ "self": null,
+ "to_port": 80
+ }
+ ],
+ "name": "carlos-test-ie",
+ "name_prefix": "HJTg",
+ "owner_id": "HdNvRrVsMW",
+ "region": "O6prSzyl9FG9gSH",
+ "revoke_rules_on_delete": null,
+ "tags": null,
+ "tags_all": {},
+ "timeouts": null,
+ "vpc_id": "FH5Ip"
+ },
+ "aws_sqs_queue.terminations": {
+ "arn": "arn:aws:sqs:eu-west-1:123456789012:carlos-test-host-terminations",
+ "content_based_deduplication": null,
+ "deduplication_scope": "JSoIGMs",
+ "delay_seconds": null,
+ "fifo_queue": null,
+ "fifo_throughput_limit": "zmXHCoYqC3J",
+ "id": "WtiB",
+ "kms_data_key_reuse_period_seconds": 0,
+ "kms_master_key_id": null,
+ "max_message_size": null,
+ "message_retention_seconds": 1209600,
+ "name": "carlos-test-host-terminations",
+ "name_prefix": "JAL9PFkPG",
+ "policy": "4mhw8",
+ "receive_wait_time_seconds": null,
+ "redrive_allow_policy": "bFz5SMJXsOg2",
+ "redrive_policy": "EqA7gxVO",
+ "region": "lYXwPxpua8WY",
+ "sqs_managed_sse_enabled": true,
+ "tags": null,
+ "tags_all": {},
+ "timeouts": null,
+ "url": "QZ15oG8m8",
+ "visibility_timeout_seconds": null
+ },
+ "aws_sqs_queue_policy.terminations": {
+ "id": "0VDztqtcXHZK",
+ "policy": "{\"Statement\":[{\"Action\":\"sqs:SendMessage\",\"Condition\":{\"ArnEquals\":{\"aws:SourceArn\":\"WEGGIHanLazS\"}},\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"events.amazonaws.com\"},\"Resource\":\"arn:aws:sqs:eu-west-1:123456789012:carlos-test-host-terminations\",\"Sid\":\"TheTerminationRuleMaySend\"},{\"Action\":\"sqs:SendMessage\",\"Condition\":{\"ArnNotEquals\":{\"aws:SourceArn\":\"WEGGIHanLazS\"}},\"Effect\":\"Deny\",\"Principal\":\"*\",\"Resource\":\"arn:aws:sqs:eu-west-1:123456789012:carlos-test-host-terminations\",\"Sid\":\"NobodyElseMaySend\"}],\"Version\":\"2012-10-17\"}",
+ "queue_url": "WtiB",
+ "region": "AOR7gRx"
+ }
+}