Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

fix(eks,ddb,ec2): autoscaling (#804)

Nahuel Nucera732381b531b4
diff --git a/README.md b/README.md
index 88664193..95457e86 100644
--- a/README.md
+++ b/README.md
@@ -90,6 +90,13 @@ curl http://localhost:4566/_ministack/ses/messages
# Filter by account (12-digit access-key ID used as the account ID)
curl "http://localhost:4566/_ministack/ses/messages?account=000000000000"
+
+# Inspect SQS messages — returns every queue's messages grouped by account
+# (includes Body, MessageId, ReceiveCount, VisibleAt, IsVisible, MessageAttributes, FIFO group/dedup)
+curl http://localhost:4566/_ministack/sqs/messages
+
+# Filter by account and/or a specific queue
+curl "http://localhost:4566/_ministack/sqs/messages?account=000000000000&QueueUrl=http://localhost:4566/000000000000/my-queue"
```
The reset endpoint is especially useful in CI pipelines and test suites — call it in `setUp`/`beforeEach` to get a clean environment for every test without restarting the container. Add `?init=1` to re-run your init scripts after the reset, restoring any resources they create (VPCs, queues, seed data, etc.).
@@ -674,6 +681,7 @@ end-to-end without any client config.
| `RDS_TMPFS_SIZE` | `256m` | Tmpfs size for RDS database containers (when `RDS_PERSIST=0`). Set to `2g` or higher for large databases |
| `GLUE_DOCKER_IMAGE` | (auto by `GlueVersion`) | Override the `amazon/aws-glue-libs` PySpark image used for Spark Glue jobs. Defaults: `glue_libs_4.0.0_image_01` (GlueVersion 4.0), `glue_libs_3.0.0_image_01` (GlueVersion 3.0) |
| `RDS_PERSIST` | `0` | Set `1` to use Docker named volumes for RDS containers instead of tmpfs. Storage grows dynamically with no fixed cap |
+| `MINISTACK_RDS_PUBLIC_ENDPOINT` | `0` | Set `1` when MiniStack itself runs in a Docker container but RDS clients connect from outside that network (remote MiniStack host, host-side clients, CI runners). `DescribeDBInstances` then returns `{MINISTACK_HOST, host_port}` — the externally-reachable host-published port — instead of the container-internal address. Set `MINISTACK_HOST` to the host clients will use |
| `DOCKER_NETWORK` | _(unset)_ | Docker network for all container-backed services (RDS, EKS, ElastiCache, Lambda). Set to your Docker Compose network name so containers can reach each other. Replaces `LAMBDA_DOCKER_NETWORK` |
| `ELASTICACHE_BASE_PORT` | `16379` | Starting host port for ElastiCache containers |
| `ELASTICACHE_CLUSTER_MODE_REAL` | `0` | Set `1` (requires `DOCKER_NETWORK`) to provision real Redis Cluster replication groups: `NumNodeGroups × (1+ReplicasPerNodeGroup)` cluster-enabled nodes wired with `redis-cli --cluster create`, serving real `CLUSTER SLOTS` / `MOVED` redirects for cluster-aware clients |
diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.py
index d7547a40..c1f2a2b1 100644
--- a/ministack/services/dynamodb.py
+++ b/ministack/services/dynamodb.py
@@ -56,6 +56,12 @@ def _conditional_check_failed(data, old_item, message="The conditional request f
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
+# Real AWS reports Export/Import as IN_PROGRESS at submit time; the flip to
+# COMPLETED happens asynchronously. We simulate that by holding IN_PROGRESS
+# on the first DescribeExport/DescribeImport calls within this grace window.
+_EXPORT_COMPLETE_AFTER_SEC = float(os.environ.get("MINISTACK_DDB_EXPORT_COMPLETE_AFTER_SEC", "1"))
+_IMPORT_COMPLETE_AFTER_SEC = float(os.environ.get("MINISTACK_DDB_IMPORT_COMPLETE_AFTER_SEC", "1"))
+
from ministack.core.persistence import PERSIST_STATE, load_state
_tables = AccountScopedDict()
@@ -2122,36 +2128,81 @@ def _partiql_insert(table, parsed):
return json_response({})
+def _partiql_key_target(table, parsed):
+ """Return (pk_key, sk_key, non_key_fn, error_resp).
+
+ AWS PartiQL UPDATE/DELETE require equality conditions on every primary key
+ attribute. Non-key clauses act as a conditional check on the targeted item
+ — failure → ConditionalCheckFailedException, not a silent no-op.
+ """
+ conditions = parsed.get("conditions") or []
+ pk_attr = table.get("pk_name")
+ sk_attr = table.get("sk_name")
+
+ pk_typed = None
+ sk_typed = None
+ rest = []
+ for attr, op, val in conditions:
+ if attr == pk_attr and op == "=":
+ pk_typed = val
+ elif sk_attr and attr == sk_attr and op == "=":
+ sk_typed = val
+ else:
+ rest.append((attr, op, val))
+
+ if pk_typed is None or (sk_attr and sk_typed is None):
+ return None, None, None, error_response_json(
+ "ValidationException",
+ "WHERE clause must specify every primary key attribute with equality.",
+ 400,
+ )
+
+ def non_key_fn(item):
+ for attr, op, val in rest:
+ if not _compare_ddb(item.get(attr), op, val):
+ return False
+ return True
+
+ pk_key = _extract_key_val(pk_typed)
+ sk_key = _extract_key_val(sk_typed) if sk_attr else "__no_sort__"
+ return pk_key, sk_key, non_key_fn, None
+
+
def _partiql_update(table, parsed):
- where_fn = parsed.get("where_fn")
set_attrs = parsed.get("set_attrs", {})
- if not where_fn or not set_attrs:
+ if not parsed.get("where_fn") or not set_attrs:
return error_response_json("ValidationException",
"UPDATE requires SET and WHERE clauses", 400)
- for pk in list(table["items"].keys()):
- for sk in list(table["items"][pk].keys()):
- it = table["items"][pk][sk]
- if where_fn(it):
- for attr, val in set_attrs.items():
- it[attr] = val
+
+ pk_key, sk_key, non_key_fn, err = _partiql_key_target(table, parsed)
+ if err:
+ return err
+
+ item = table["items"].get(pk_key, {}).get(sk_key)
+ if item is None or not non_key_fn(item):
+ return _conditional_check_failed({}, item)
+
+ for attr, val in set_attrs.items():
+ item[attr] = val
return json_response({})
def _partiql_delete(table, parsed):
- where_fn = parsed.get("where_fn")
- if not where_fn:
+ if not parsed.get("where_fn"):
return error_response_json("ValidationException",
"DELETE requires a WHERE clause", 400)
- to_delete = []
- for pk in list(table["items"].keys()):
- for sk in list(table["items"][pk].keys()):
- it = table["items"][pk][sk]
- if where_fn(it):
- to_delete.append((pk, sk))
- for pk, sk in to_delete:
- del table["items"][pk][sk]
- if not table["items"][pk]:
- del table["items"][pk]
+
+ pk_key, sk_key, non_key_fn, err = _partiql_key_target(table, parsed)
+ if err:
+ return err
+
+ item = table["items"].get(pk_key, {}).get(sk_key)
+ if item is None or not non_key_fn(item):
+ return _conditional_check_failed({}, item)
+
+ del table["items"][pk_key][sk_key]
+ if not table["items"][pk_key]:
+ del table["items"][pk_key]
_update_counts(table)
return json_response({})
@@ -2360,9 +2411,11 @@ def _parse_partiql_select(s, parameters):
if proj_str != "*":
projections = [p.strip().strip('"') for p in proj_str.split(",")]
- where_fn = _build_partiql_where(where_str, parameters) if where_str else None
+ where_fn, conditions = (_build_partiql_where(where_str, parameters)
+ if where_str else (None, []))
- return {"op": "SELECT", "table": table_name, "projections": projections, "where_fn": where_fn}
+ return {"op": "SELECT", "table": table_name, "projections": projections,
+ "where_fn": where_fn, "conditions": conditions}
def _parse_partiql_insert(s, parameters):
@@ -2408,8 +2461,9 @@ def _parse_partiql_update(s, parameters):
val_str = parts[1].strip()
set_attrs[attr] = _parse_partiql_literal(val_str, parameters, param_idx)
- where_fn = _build_partiql_where(where_str, parameters, param_idx)
- return {"op": "UPDATE", "table": table_name, "set_attrs": set_attrs, "where_fn": where_fn}
+ where_fn, conditions = _build_partiql_where(where_str, parameters, param_idx)
+ return {"op": "UPDATE", "table": table_name, "set_attrs": set_attrs,
+ "where_fn": where_fn, "conditions": conditions}
def _parse_partiql_delete(s, parameters):
@@ -2424,18 +2478,18 @@ def _parse_partiql_delete(s, parameters):
table_name = m.group(1).strip()
where_str = m.group(2).strip()
- where_fn = _build_partiql_where(where_str, parameters)
- return {"op": "DELETE", "table": table_name, "where_fn": where_fn}
+ where_fn, conditions = _build_partiql_where(where_str, parameters)
+ return {"op": "DELETE", "table": table_name, "where_fn": where_fn,
+ "conditions": conditions}
def _build_partiql_where(where_str, parameters, param_idx=None):
- """Build a predicate function from a PartiQL WHERE clause."""
+ """Build a predicate function + structural conditions list for a PartiQL WHERE."""
if not where_str or not where_str.strip():
- return None
+ return None, []
if param_idx is None:
param_idx = [0]
- # Parse simple conditions: attr op value [AND attr op value ...]
conditions = _parse_partiql_conditions(where_str, parameters, param_idx)
def where_fn(item):
@@ -2445,7 +2499,7 @@ def _build_partiql_where(where_str, parameters, param_idx=None):
return False
return True
- return where_fn
+ return where_fn, conditions
def _parse_partiql_conditions(where_str, parameters, param_idx):
@@ -3665,7 +3719,7 @@ def _describe_export(data):
if not desc:
return error_response_json("ExportNotFoundException",
f"Export not found: {arn}", 400)
- if desc.get("ExportStatus") == "IN_PROGRESS":
+ if desc.get("ExportStatus") == "IN_PROGRESS" and (time.time() - desc.get("StartTime", 0)) >= _EXPORT_COMPLETE_AFTER_SEC:
table_name = _table_name_from_arn(desc["TableArn"])
table = _tables.get(table_name)
if table:
@@ -3738,13 +3792,12 @@ def _import_table(data):
now = time.time()
desc = {
"ImportArn": arn,
- "ImportStatus": "COMPLETED",
+ "ImportStatus": "IN_PROGRESS",
"TableArn": table_arn,
"TableId": table_id,
"S3BucketSource": s3_source,
"InputFormat": fmt,
"StartTime": now,
- "EndTime": now,
"ProcessedSizeBytes": 0,
"ProcessedItemCount": 0,
"ImportedItemCount": 0,
@@ -3770,6 +3823,9 @@ def _describe_import(data):
if not desc:
return error_response_json("ImportNotFoundException",
f"Import not found: {arn}", 400)
+ if desc.get("ImportStatus") == "IN_PROGRESS" and (time.time() - desc.get("StartTime", 0)) >= _IMPORT_COMPLETE_AFTER_SEC:
+ desc["ImportStatus"] = "COMPLETED"
+ desc["EndTime"] = time.time()
return json_response({"ImportTableDescription": desc})
diff --git a/ministack/services/ec2.py b/ministack/services/ec2.py
index ae1b58a3..35251b65 100644
--- a/ministack/services/ec2.py
+++ b/ministack/services/ec2.py
@@ -4683,18 +4683,15 @@ def _delete_launch_template(p):
</launchTemplate>""")
-def _fleet_instances_xml(instances_list, configs):
+def _fleet_instances_xml(instances_list):
instances_xml = []
for item in instances_list:
inst_ids_xml = "".join(f"<item>{_esc(iid)}</item>" for iid in item["InstanceIds"])
- lt_and_overrides_xml = ""
- if configs:
- cfg = configs[0]
- spec = cfg.get("LaunchTemplateSpecification", {})
- lt_id_val = spec.get("LaunchTemplateId") or ""
- lt_name_val = spec.get("LaunchTemplateName") or ""
- version_val = spec.get("Version") or "$Default"
- lt_and_overrides_xml = f"""
+ spec = item.get("LaunchTemplateSpec") or {}
+ lt_id_val = spec.get("LaunchTemplateId") or ""
+ lt_name_val = spec.get("LaunchTemplateName") or ""
+ version_val = spec.get("Version") or "$Default"
+ lt_and_overrides_xml = f"""
<launchTemplateAndOverrides>
<launchTemplateSpecification>
<launchTemplateId>{_esc(lt_id_val)}</launchTemplateId>
@@ -4702,7 +4699,7 @@ def _fleet_instances_xml(instances_list, configs):
<version>{_esc(version_val)}</version>
</launchTemplateSpecification>
</launchTemplateAndOverrides>
- """
+ """ if (lt_id_val or lt_name_val) else ""
instances_xml.append(f"""<item>
{lt_and_overrides_xml}
<lifecycle>{_esc(item["Lifecycle"])}</lifecycle>
@@ -4712,6 +4709,54 @@ def _fleet_instances_xml(instances_list, configs):
return "".join(instances_xml)
+def _resolve_launch_template_data(spec):
+ """Resolve a LaunchTemplateSpecification dict to (lt_data, lt_record, error)."""
+ lt_id = spec.get("LaunchTemplateId")
+ lt_name = spec.get("LaunchTemplateName")
+ version_str = spec.get("Version") or "$Default"
+
+ lt = None
+ if lt_id:
+ lt = _launch_templates.get(lt_id)
+ elif lt_name:
+ for t in _launch_templates.values():
+ if t["LaunchTemplateName"] == lt_name:
+ lt = t
+ break
+
+ if (lt_id or lt_name) and not lt:
+ return None, None, _error(
+ "InvalidLaunchTemplateId.NotFoundException",
+ f"The launch template '{lt_id or lt_name}' does not exist",
+ 400,
+ )
+
+ if not lt:
+ return {}, None, None
+
+ versions = lt.get("Versions", [])
+ target_ver = 1
+ if version_str == "$Default":
+ target_ver = lt.get("DefaultVersionNumber", 1)
+ elif version_str == "$Latest":
+ target_ver = lt.get("LatestVersionNumber", 1)
+ else:
+ try:
+ target_ver = int(version_str)
+ except ValueError:
+ target_ver = 1
+
+ version = None
+ for v in versions:
+ if v["VersionNumber"] == target_ver:
+ version = v
+ break
+ if not version and versions:
+ version = versions[0]
+
+ return (version or {}).get("LaunchTemplateData", {}) or {}, lt, None
+
+
def _create_fleet(p):
fleet_type = _p(p, "Type") or "maintain"
total_capacity = int(
@@ -4720,6 +4765,13 @@ def _create_fleet(p):
or _p(p, "TargetCapacitySpecification.SpotTargetCapacity")
or "1"
)
+ # AWS derives Spot vs On-Demand from DefaultTargetCapacityType, not from
+ # FleetType (which is {request, maintain, instant}).
+ default_capacity_type = (
+ _p(p, "TargetCapacitySpecification.DefaultTargetCapacityType") or "on-demand"
+ ).lower()
+ is_spot = default_capacity_type == "spot"
+ lifecycle = "spot" if is_spot else "on-demand"
# Parse LaunchTemplateConfigs
configs = []
@@ -4756,171 +4808,163 @@ def _create_fleet(p):
})
i += 1
- # Resolve settings from the first launch template configuration
- image_id = "ami-00000000"
- instance_type = "t2.micro"
- subnet_id = _DEFAULT_SUBNET_ID
- key_name = ""
- user_data = ""
- sg_ids = None
- iam_profile = None
-
- if configs:
- cfg = configs[0]
+ # Resolve LT data per config (so multi-config fleets work).
+ resolved_configs = [] # list of (spec, lt_data) per config
+ for cfg in configs:
spec = cfg["LaunchTemplateSpecification"]
- lt_id = spec.get("LaunchTemplateId")
- lt_name = spec.get("LaunchTemplateName")
- version_str = spec.get("Version") or "$Default"
-
- lt = None
- if lt_id:
- lt = _launch_templates.get(lt_id)
- elif lt_name:
- for t in _launch_templates.values():
- if t["LaunchTemplateName"] == lt_name:
- lt = t
- lt_id = lt["LaunchTemplateId"]
- break
-
- if (lt_id or lt_name) and not lt:
- return _error(
- "InvalidLaunchTemplateId.NotFoundException",
- f"The launch template '{lt_id or lt_name}' does not exist",
- 400
- )
+ lt_data, _lt, err = _resolve_launch_template_data(spec)
+ if err:
+ return err
+ resolved_configs.append((spec, lt_data, cfg.get("Overrides") or []))
+
+ # Build the (config, override) slot list — one slot per override per config,
+ # or a single slot per config when no overrides were specified.
+ slots = [] # list of dicts: {spec, image_id, instance_type, subnet_id, key_name, user_data, sg_ids, iam_profile}
+ for spec, lt_data, overrides in resolved_configs:
+ base = _slot_from_lt_data(spec, lt_data)
+ if overrides:
+ for ov in overrides:
+ slot = dict(base)
+ if ov.get("InstanceType"):
+ slot["instance_type"] = ov["InstanceType"]
+ if ov.get("SubnetId"):
+ slot["subnet_id"] = ov["SubnetId"]
+ slots.append(slot)
+ else:
+ slots.append(base)
- if lt:
- versions = lt.get("Versions", [])
- target_ver = 1
- if version_str == "$Default":
- target_ver = lt.get("DefaultVersionNumber", 1)
- elif version_str == "$Latest":
- target_ver = lt.get("LatestVersionNumber", 1)
- else:
- try:
- target_ver = int(version_str)
- except ValueError:
- target_ver = 1
-
- version = None
- for v in versions:
- if v["VersionNumber"] == target_ver:
- version = v
- break
- if not version and versions:
- version = versions[0]
-
- if version:
- lt_data = version.get("LaunchTemplateData", {})
- image_id = lt_data.get("ImageId") or image_id
- instance_type = lt_data.get("InstanceType") or instance_type
- subnet_id = lt_data.get("SubnetId") or subnet_id
- key_name = lt_data.get("KeyName") or key_name
- user_data = lt_data.get("UserData") or user_data
- sg_ids = lt_data.get("SecurityGroupIds") or sg_ids
-
- lt_iam = lt_data.get("IamInstanceProfile", {})
- iam_arn = lt_iam.get("Arn")
- iam_name = lt_iam.get("Name")
- if iam_arn or iam_name:
- if not iam_arn and iam_name:
- iam_arn = f"arn:aws:iam::{get_account_id()}:instance-profile/{iam_name}"
- iam_id = "AIPA" + new_uuid().replace("-", "").upper()[:17]
- iam_profile = {"Arn": iam_arn, "Id": iam_id}
-
- # Apply overrides
- if cfg.get("Overrides"):
- override = cfg["Overrides"][0]
- if override.get("InstanceType"):
- instance_type = override["InstanceType"]
- if override.get("SubnetId"):
- subnet_id = override["SubnetId"]
-
- # Launch instances
- launched = _launch_instances_internal(
- image_id=image_id,
- instance_type=instance_type,
- subnet_id=subnet_id,
- count=total_capacity,
- key_name=key_name,
- user_data=user_data,
- sg_ids=sg_ids,
- iam_profile=iam_profile,
- )
+ if not slots:
+ slots.append(_slot_from_lt_data({}, {}))
- # Process tag specifications
+ # Process tag specifications (AWS uses TagSpecifications, not TagSpecification)
fleet_tags = []
instance_tags = []
- i = 1
- while _p(p, f"TagSpecification.{i}.ResourceType"):
- rtype = _p(p, f"TagSpecification.{i}.ResourceType")
- spec_tags = []
- j = 1
- while _p(p, f"TagSpecification.{i}.Tag.{j}.Key"):
- spec_tags.append({
- "Key": _p(p, f"TagSpecification.{i}.Tag.{j}.Key"),
- "Value": _p(p, f"TagSpecification.{i}.Tag.{j}.Value", ""),
- })
- j += 1
- if rtype == "fleet":
- fleet_tags.extend(spec_tags)
- elif rtype == "instance":
- instance_tags.extend(spec_tags)
- i += 1
-
- if instance_tags:
- for inst in launched:
- _tags[inst["InstanceId"]] = instance_tags[:]
+ for tag_prefix in ("TagSpecification", "TagSpecifications"):
+ i = 1
+ while _p(p, f"{tag_prefix}.{i}.ResourceType"):
+ rtype = _p(p, f"{tag_prefix}.{i}.ResourceType")
+ spec_tags = []
+ for tag_key in ("Tag", "Tags"):
+ j = 1
+ while _p(p, f"{tag_prefix}.{i}.{tag_key}.{j}.Key"):
+ spec_tags.append({
+ "Key": _p(p, f"{tag_prefix}.{i}.{tag_key}.{j}.Key"),
+ "Value": _p(p, f"{tag_prefix}.{i}.{tag_key}.{j}.Value", ""),
+ })
+ j += 1
+ if rtype == "fleet":
+ fleet_tags.extend(spec_tags)
+ elif rtype == "instance":
+ instance_tags.extend(spec_tags)
+ i += 1
fleet_id = "fleet-" + new_uuid()
+
+ # AWS launches synchronously and returns Instances only when Type=instant.
+ # For maintain/request, fleets fulfil asynchronously — return FleetId alone.
+ instance_items = []
+ if fleet_type == "instant":
+ # Round-robin distribute total_capacity across slots.
+ slot_buckets = [[] for _ in slots]
+ for k in range(total_capacity):
+ slot_idx = k % len(slots)
+ slot = slots[slot_idx]
+ launched = _launch_instances_internal(
+ image_id=slot["image_id"],
+ instance_type=slot["instance_type"],
+ subnet_id=slot["subnet_id"],
+ count=1,
+ key_name=slot["key_name"],
+ user_data=slot["user_data"],
+ sg_ids=slot["sg_ids"],
+ iam_profile=slot["iam_profile"],
+ )
+ slot_buckets[slot_idx].extend(launched)
+ for slot, launched in zip(slots, slot_buckets):
+ if not launched:
+ continue
+ if instance_tags:
+ for inst in launched:
+ _tags[inst["InstanceId"]] = instance_tags[:]
+ instance_items.append({
+ "InstanceIds": [inst["InstanceId"] for inst in launched],
+ "InstanceType": slot["instance_type"],
+ "Lifecycle": lifecycle,
+ "LaunchTemplateSpec": slot["spec"],
+ })
+
if fleet_tags:
_tags[fleet_id] = fleet_tags
now_iso = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
+ fulfilled_total = float(total_capacity) if fleet_type == "instant" else 0.0
fleet_record = {
"FleetId": fleet_id,
"FleetState": "active",
- "ActivityStatus": "fulfilled",
+ "ActivityStatus": "fulfilled" if fleet_type == "instant" else "pending_fulfillment",
"CreateTime": now_iso,
"Type": fleet_type,
- "FulfilledCapacity": float(total_capacity),
- "FulfilledOnDemandCapacity": float(total_capacity) if fleet_type != "spot" else 0.0,
+ "FulfilledCapacity": fulfilled_total,
+ "FulfilledOnDemandCapacity": fulfilled_total if not is_spot else 0.0,
"TargetCapacitySpecification": {
"TotalTargetCapacity": total_capacity,
- "OnDemandTargetCapacity": total_capacity if fleet_type != "spot" else 0,
- "SpotTargetCapacity": total_capacity if fleet_type == "spot" else 0,
- "DefaultTargetCapacityType": "on-demand" if fleet_type != "spot" else "spot",
+ "OnDemandTargetCapacity": total_capacity if not is_spot else 0,
+ "SpotTargetCapacity": total_capacity if is_spot else 0,
+ "DefaultTargetCapacityType": default_capacity_type,
},
"LaunchTemplateConfigs": configs,
- "Instances": [
- {
- "InstanceIds": [inst["InstanceId"] for inst in launched],
- "InstanceType": instance_type,
- "Lifecycle": "on-demand" if fleet_type != "spot" else "spot",
- }
- ],
+ "Instances": instance_items,
"Tags": fleet_tags,
}
_fleets[fleet_id] = fleet_record
- instances_xml_str = _fleet_instances_xml(fleet_record["Instances"], configs)
- inner = f"""<fleetId>{_esc(fleet_id)}</fleetId>
- <fleetInstanceSet>{instances_xml_str}</fleetInstanceSet>
- <errorSet/>"""
- return _xml(200, "CreateFleetResponse", inner)
+ inner_parts = [f"<fleetId>{_esc(fleet_id)}</fleetId>"]
+ if fleet_type == "instant":
+ inner_parts.append(f"<fleetInstanceSet>{_fleet_instances_xml(instance_items)}</fleetInstanceSet>")
+ inner_parts.append("<errorSet/>")
+ return _xml(200, "CreateFleetResponse", "\n ".join(inner_parts))
+
+
+def _slot_from_lt_data(spec, lt_data):
+ """Build a launch slot from a resolved LaunchTemplateData dict + spec."""
+ iam_profile = None
+ lt_iam = (lt_data or {}).get("IamInstanceProfile", {}) or {}
+ iam_arn = lt_iam.get("Arn")
+ iam_name = lt_iam.get("Name")
+ if iam_arn or iam_name:
+ if not iam_arn and iam_name:
+ iam_arn = f"arn:aws:iam::{get_account_id()}:instance-profile/{iam_name}"
+ iam_id = "AIPA" + new_uuid().replace("-", "").upper()[:17]
+ iam_profile = {"Arn": iam_arn, "Id": iam_id}
+ return {
+ "spec": spec or {},
+ "image_id": (lt_data or {}).get("ImageId") or "ami-00000000",
+ "instance_type": (lt_data or {}).get("InstanceType") or "t2.micro",
+ "subnet_id": (lt_data or {}).get("SubnetId") or _DEFAULT_SUBNET_ID,
+ "key_name": (lt_data or {}).get("KeyName") or "",
+ "user_data": (lt_data or {}).get("UserData") or "",
+ "sg_ids": (lt_data or {}).get("SecurityGroupIds") or None,
+ "iam_profile": iam_profile,
+ }
def _describe_fleets(p):
fleet_ids = _parse_member_list(p, "FleetId")
- results = []
- for f in _fleets.values():
- if fleet_ids and f["FleetId"] not in fleet_ids:
- continue
- results.append(f)
+ if fleet_ids:
+ missing = [fid for fid in fleet_ids if fid not in _fleets]
+ if missing:
+ return _error(
+ "InvalidFleetId.NotFound",
+ f"The fleet ID '{missing[0]}' does not exist",
+ 400,
+ )
+ results = [_fleets[fid] for fid in fleet_ids]
+ else:
+ results = list(_fleets.values())
items = []
for f in results:
- instances_xml_str = _fleet_instances_xml(f["Instances"], f["LaunchTemplateConfigs"])
+ instances_xml_str = _fleet_instances_xml(f["Instances"])
tag_set_xml = _tag_set_xml(f["FleetId"])
tcs = f["TargetCapacitySpecification"]
items.append(f"""<item>
diff --git a/ministack/services/eks.py b/ministack/services/eks.py
index 3bab25cb..514ad210 100644
--- a/ministack/services/eks.py
+++ b/ministack/services/eks.py
@@ -918,7 +918,9 @@ def _restart_k3s(cluster_name, oidc_args=None, idp_cfg_refs=None):
if not client:
return
- cluster["status"] = "UPDATING"
+ # Real AWS keeps cluster status ACTIVE during IdP changes — the work is
+ # carried in the Update record, not on the cluster itself. Mutate cfg state
+ # only.
oidc_args = oidc_args or []
idp_cfg_refs = idp_cfg_refs or []
@@ -963,11 +965,9 @@ def _restart_k3s(cluster_name, oidc_args=None, idp_cfg_refs=None):
cluster["endpoint"] = ep
cluster["certificateAuthority"]["data"] = _extract_ca_cert(container)
- cluster["status"] = "ACTIVE"
_mark_idp_active()
except Exception as e:
logger.warning("EKS: failed to restart k3s for %s — falling back to mock: %s", cluster_name, e)
- cluster["status"] = "ACTIVE"
cluster["certificateAuthority"]["data"] = base64.b64encode(b"MOCK-CA-CERTIFICATE").decode()
cluster["endpoint"] = f"https://localhost:{port}"
_mark_idp_active()
@@ -991,20 +991,33 @@ def _associate_identity_provider_config(cluster_name, body):
if not oidc.get("issuerUrl") or not oidc.get("clientId"):
return _error(400, "InvalidParameterException", "issuerUrl and clientId are required inside oidc config.")
+ # AWS allows only one OIDC IdP config per cluster regardless of name —
+ # this covers same-name and different-name duplicates in one check.
+ for existing_key in _idp_configs.keys():
+ if existing_key.startswith(f"{cluster_name}\x00"):
+ return _error(409, "ResourceInUseException", f"Cluster '{cluster_name}' already has an OIDC identity provider configuration.")
key = f"{cluster_name}\x00{idp_name}"
- if key in _idp_configs:
- return _error(409, "ResourceInUseException", f"OIDC provider configuration '{idp_name}' already exists on cluster '{cluster_name}'.")
arn = (
f"arn:aws:eks:{get_region()}:{get_account_id()}"
f":identityproviderconfig/{cluster_name}/oidc/{idp_name}/{new_uuid()}"
)
+ tags = body.get("tags") or {}
_idp_configs[key] = {
"oidc": oidc,
"status": "CREATING",
- "tags": body.get("tags") or {},
+ "tags": tags,
"arn": arn,
}
+ if tags:
+ _tags[arn] = dict(tags)
+
+ logger.warning(
+ "EKS: AssociateIdentityProviderConfig on cluster %s triggers a k3s restart "
+ "which wipes in-cluster workloads (Pods/Deployments/Services). "
+ "Local-emulator limitation — real AWS rolls config without affecting the data plane.",
+ cluster_name,
+ )
oidc_args, idp_cfg_refs = _collect_oidc_state(cluster_name)
_restart_k3s(cluster_name, oidc_args=oidc_args, idp_cfg_refs=idp_cfg_refs)
@@ -1067,7 +1080,17 @@ def _disassociate_identity_provider_config(cluster_name, body):
if key not in _idp_configs:
return _error(404, "ResourceNotFoundException", f"OIDC provider configuration '{name}' not found on cluster '{cluster_name}'.")
- _idp_configs.pop(key, None)
+ removed = _idp_configs.pop(key, None)
+ if removed and removed.get("arn"):
+ _tags.pop(removed["arn"], None)
+
+ logger.warning(
+ "EKS: DisassociateIdentityProviderConfig on cluster %s triggers a k3s restart "
+ "which wipes in-cluster workloads (Pods/Deployments/Services). "
+ "Local-emulator limitation — real AWS rolls config without affecting the data plane.",
+ cluster_name,
+ )
+
oidc_args, idp_cfg_refs = _collect_oidc_state(cluster_name)
_restart_k3s(cluster_name, oidc_args=oidc_args, idp_cfg_refs=idp_cfg_refs)
diff --git a/ministack/services/rds.py b/ministack/services/rds.py
index e4dedd8e..0b8d49b1 100644
--- a/ministack/services/rds.py
+++ b/ministack/services/rds.py
@@ -53,6 +53,12 @@ BASE_PORT = int(os.environ.get("RDS_BASE_PORT", "15432"))
RDS_TMPFS_SIZE = os.environ.get("RDS_TMPFS_SIZE", "256m")
RDS_PERSIST = os.environ.get("RDS_PERSIST", "0").lower() in ("1", "true", "yes")
DOCKER_NETWORK = os.environ.get("DOCKER_NETWORK", "")
+# When set, skip ministack's own Docker network auto-detect so DescribeDBInstances
+# returns {MINISTACK_HOST, host_port} — the address that's actually reachable
+# from outside the Docker network (remote ministack deployments, host-side
+# clients of a containerised ministack). Off by default: existing in-network
+# behavior unchanged.
+RDS_PUBLIC_ENDPOINT = os.environ.get("MINISTACK_RDS_PUBLIC_ENDPOINT", "0").lower() in ("1", "true", "yes")
_instances = AccountScopedDict()
_clusters = AccountScopedDict()
@@ -278,8 +284,16 @@ def _get_docker():
def _get_ministack_network(docker_client):
- """Detect the Docker network MiniStack is running on (if containerised)."""
+ """Detect the Docker network MiniStack is running on (if containerised).
+
+ Honors MINISTACK_RDS_PUBLIC_ENDPOINT — when set, returns None so the
+ DescribeDBInstances endpoint resolves to {MINISTACK_HOST, host_port}
+ instead of the container-internal address (useful for remote-ministack
+ deployments where external clients can't reach the Docker network).
+ """
global _ministack_network
+ if RDS_PUBLIC_ENDPOINT:
+ return None
if _ministack_network is not None:
return _ministack_network or None
if DOCKER_NETWORK:
diff --git a/tests/test_dynamodb.py b/tests/test_dynamodb.py
index f96d275f..456db9e9 100644
--- a/tests/test_dynamodb.py
+++ b/tests/test_dynamodb.py
@@ -2919,6 +2919,10 @@ def test_dynamodb_export_table_to_point_in_time(ddb):
assert desc["ExportStatus"] == "IN_PROGRESS"
export_arn = desc["ExportArn"]
+ # Export flips to COMPLETED only after the IN_PROGRESS grace window
+ # (MINISTACK_DDB_EXPORT_COMPLETE_AFTER_SEC, default 1s) — matches real
+ # AWS, which reports IN_PROGRESS at submit time.
+ time.sleep(1.2)
d = ddb.describe_export(ExportArn=export_arn)
assert d["ExportDescription"]["ExportArn"] == export_arn
assert d["ExportDescription"]["ExportStatus"] == "COMPLETED"
@@ -5208,3 +5212,119 @@ def test_dynamodb_batch_write_cap_message_includes_count(ddb):
assert "30" in msg or "25" in msg
finally:
ddb.delete_table(TableName=name)
+
+
+# ---------------------------------------------------------------------------
+# PartiQL: non-key predicate failures map to ConditionalCheckFailedException
+# ---------------------------------------------------------------------------
+
+def test_partiql_update_false_non_key_predicate_returns_ccf(ddb):
+ name = "partiql-upd-ccf"
+ _basic_table(ddb, name)
+ try:
+ ddb.put_item(TableName=name, Item={"pk": {"S": "x"}, "name": {"S": "alpha"}, "n": {"N": "1"}})
+ with pytest.raises(ClientError) as exc:
+ ddb.execute_statement(
+ Statement=f'UPDATE "{name}" SET n = 9 WHERE pk = \'x\' AND name = \'beta\''
+ )
+ assert exc.value.response["Error"]["Code"] == "ConditionalCheckFailedException"
+ after = ddb.get_item(TableName=name, Key={"pk": {"S": "x"}})["Item"]
+ assert after["n"]["N"] == "1"
+ finally:
+ ddb.delete_table(TableName=name)
+
+
+def test_partiql_delete_false_non_key_predicate_returns_ccf(ddb):
+ name = "partiql-del-ccf"
+ _basic_table(ddb, name)
+ try:
+ ddb.put_item(TableName=name, Item={"pk": {"S": "x"}, "name": {"S": "alpha"}})
+ with pytest.raises(ClientError) as exc:
+ ddb.execute_statement(
+ Statement=f'DELETE FROM "{name}" WHERE pk = \'x\' AND name = \'beta\''
+ )
+ assert exc.value.response["Error"]["Code"] == "ConditionalCheckFailedException"
+ still = ddb.get_item(TableName=name, Key={"pk": {"S": "x"}}).get("Item")
+ assert still is not None
+ finally:
+ ddb.delete_table(TableName=name)
+
+
+def test_partiql_update_missing_pk_clause_returns_validation(ddb):
+ """AWS PartiQL UPDATE requires every PK attribute as an equality predicate."""
+ name = "partiql-upd-nopk"
+ _basic_table(ddb, name, with_sk=True)
+ try:
+ ddb.put_item(TableName=name, Item={"pk": {"S": "x"}, "sk": {"S": "1"}, "n": {"N": "1"}})
+ with pytest.raises(ClientError) as exc:
+ ddb.execute_statement(
+ Statement=f'UPDATE "{name}" SET n = 9 WHERE pk = \'x\''
+ )
+ assert exc.value.response["Error"]["Code"] == "ValidationException"
+ finally:
+ ddb.delete_table(TableName=name)
+
+
+# ---------------------------------------------------------------------------
+# Export/Import: IN_PROGRESS at submit, COMPLETED after delay
+# ---------------------------------------------------------------------------
+
+def test_export_returns_in_progress_then_completed(ddb, s3):
+ name = "exp-in-progress"
+ _basic_table(ddb, name)
+ bucket = f"exp-bucket-{_uuid_mod.uuid4().hex[:8]}"
+ s3.create_bucket(Bucket=bucket)
+ try:
+ ddb.update_continuous_backups(
+ TableName=name,
+ PointInTimeRecoverySpecification={"PointInTimeRecoveryEnabled": True},
+ )
+ table_arn = ddb.describe_table(TableName=name)["Table"]["TableArn"]
+ resp = ddb.export_table_to_point_in_time(TableArn=table_arn, S3Bucket=bucket)
+ export_arn = resp["ExportDescription"]["ExportArn"]
+ assert resp["ExportDescription"]["ExportStatus"] == "IN_PROGRESS"
+
+ first = ddb.describe_export(ExportArn=export_arn)["ExportDescription"]
+ assert first["ExportStatus"] == "IN_PROGRESS"
+
+ time.sleep(1.2)
+ later = ddb.describe_export(ExportArn=export_arn)["ExportDescription"]
+ assert later["ExportStatus"] == "COMPLETED"
+ assert "EndTime" in later
+ finally:
+ try:
+ ddb.delete_table(TableName=name)
+ except Exception:
+ pass
+
+
+def test_import_returns_in_progress_then_completed(ddb, s3):
+ bucket = f"imp-bucket-{_uuid_mod.uuid4().hex[:8]}"
+ s3.create_bucket(Bucket=bucket)
+ tname = f"imp-in-progress-{_uuid_mod.uuid4().hex[:8]}"
+ try:
+ resp = ddb.import_table(
+ S3BucketSource={"S3Bucket": bucket},
+ InputFormat="DYNAMODB_JSON",
+ TableCreationParameters={
+ "TableName": tname,
+ "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
+ "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
+ "BillingMode": "PAY_PER_REQUEST",
+ },
+ )
+ import_arn = resp["ImportTableDescription"]["ImportArn"]
+ assert resp["ImportTableDescription"]["ImportStatus"] == "IN_PROGRESS"
+
+ first = ddb.describe_import(ImportArn=import_arn)["ImportTableDescription"]
+ assert first["ImportStatus"] == "IN_PROGRESS"
+
+ time.sleep(1.2)
+ later = ddb.describe_import(ImportArn=import_arn)["ImportTableDescription"]
+ assert later["ImportStatus"] == "COMPLETED"
+ assert "EndTime" in later
+ finally:
+ try:
+ ddb.delete_table(TableName=tname)
+ except Exception:
+ pass
diff --git a/tests/test_ec2.py b/tests/test_ec2.py
index e37b473e..512a5fb2 100644
--- a/tests/test_ec2.py
+++ b/tests/test_ec2.py
@@ -2184,3 +2184,98 @@ def test_ec2_create_describe_fleet(ec2):
assert f["TargetCapacitySpecification"]["TotalTargetCapacity"] == 2
assert any(t["Key"] == "Environment" and t["Value"] == "Production" for t in f.get("Tags", []))
+
+def test_create_fleet_default_capacity_type_spot(ec2):
+ """DefaultTargetCapacityType=spot drives lifecycle + capacity-slot accounting,
+ not the top-level Type (which is {request, maintain, instant})."""
+ lt = ec2.create_launch_template(
+ LaunchTemplateName=f"spot-lt-{_uuid_mod.uuid4().hex[:8]}",
+ LaunchTemplateData={"ImageId": "ami-deadbeef", "InstanceType": "t3.small"},
+ )
+ lt_id = lt["LaunchTemplate"]["LaunchTemplateId"]
+ resp = ec2.create_fleet(
+ LaunchTemplateConfigs=[{
+ "LaunchTemplateSpecification": {"LaunchTemplateId": lt_id, "Version": "1"},
+ }],
+ TargetCapacitySpecification={
+ "TotalTargetCapacity": 2,
+ "SpotTargetCapacity": 2,
+ "DefaultTargetCapacityType": "spot",
+ },
+ Type="instant",
+ )
+ desc = ec2.describe_fleets(FleetIds=[resp["FleetId"]])["Fleets"][0]
+ tcs = desc["TargetCapacitySpecification"]
+ assert tcs["DefaultTargetCapacityType"] == "spot"
+ assert tcs["SpotTargetCapacity"] == 2
+ assert tcs["OnDemandTargetCapacity"] == 0
+ assert desc["Instances"][0]["Lifecycle"] == "spot"
+
+
+def test_create_fleet_distributes_across_configs_and_overrides(ec2):
+ """Multi-config × multi-override should produce one Instances[*] item
+ per (config, override) bucket, with capacity round-robin'd across them."""
+ lt1 = ec2.create_launch_template(
+ LaunchTemplateName=f"multi-lt1-{_uuid_mod.uuid4().hex[:8]}",
+ LaunchTemplateData={"ImageId": "ami-aaaaaaaa", "InstanceType": "t3.micro"},
+ )["LaunchTemplate"]["LaunchTemplateId"]
+ lt2 = ec2.create_launch_template(
+ LaunchTemplateName=f"multi-lt2-{_uuid_mod.uuid4().hex[:8]}",
+ LaunchTemplateData={"ImageId": "ami-bbbbbbbb", "InstanceType": "t3.micro"},
+ )["LaunchTemplate"]["LaunchTemplateId"]
+ resp = ec2.create_fleet(
+ LaunchTemplateConfigs=[
+ {
+ "LaunchTemplateSpecification": {"LaunchTemplateId": lt1, "Version": "1"},
+ "Overrides": [
+ {"InstanceType": "t3.small"},
+ {"InstanceType": "t3.medium"},
+ ],
+ },
+ {
+ "LaunchTemplateSpecification": {"LaunchTemplateId": lt2, "Version": "1"},
+ "Overrides": [
+ {"InstanceType": "t3.large"},
+ {"InstanceType": "t3.xlarge"},
+ ],
+ },
+ ],
+ TargetCapacitySpecification={"TotalTargetCapacity": 4, "OnDemandTargetCapacity": 4},
+ Type="instant",
+ )
+ instance_types = sorted(i["InstanceType"] for i in resp["Instances"])
+ assert instance_types == ["t3.large", "t3.medium", "t3.small", "t3.xlarge"]
+ total_ids = [iid for item in resp["Instances"] for iid in item["InstanceIds"]]
+ assert len(total_ids) == 4
+
+
+def test_create_fleet_maintain_returns_fleetid_only(ec2):
+ """For Type=maintain (and request), AWS does not launch synchronously —
+ response carries FleetId only; no Instances / no Errors."""
+ lt = ec2.create_launch_template(
+ LaunchTemplateName=f"maintain-lt-{_uuid_mod.uuid4().hex[:8]}",
+ LaunchTemplateData={"ImageId": "ami-11111111", "InstanceType": "t2.micro"},
+ )["LaunchTemplate"]["LaunchTemplateId"]
+ resp = ec2.create_fleet(
+ LaunchTemplateConfigs=[{
+ "LaunchTemplateSpecification": {"LaunchTemplateId": lt, "Version": "1"},
+ }],
+ TargetCapacitySpecification={"TotalTargetCapacity": 3, "OnDemandTargetCapacity": 3},
+ Type="maintain",
+ )
+ assert resp["FleetId"].startswith("fleet-")
+ assert not resp.get("Instances")
+ assert not resp.get("Errors")
+ desc = ec2.describe_fleets(FleetIds=[resp["FleetId"]])["Fleets"][0]
+ assert desc["Type"] == "maintain"
+ assert desc["FulfilledCapacity"] == 0.0
+ assert desc["ActivityStatus"] == "pending_fulfillment"
+ assert desc.get("Instances", []) == []
+
+
+def test_describe_fleets_unknown_id_returns_invalid_fleet_id(ec2):
+ bogus = f"fleet-{_uuid_mod.uuid4().hex}"
+ with pytest.raises(ClientError) as exc:
+ ec2.describe_fleets(FleetIds=[bogus])
+ assert exc.value.response["Error"]["Code"] == "InvalidFleetId.NotFound"
+
diff --git a/tests/test_eks.py b/tests/test_eks.py
index 180f9bf3..f0395a0b 100644
--- a/tests/test_eks.py
+++ b/tests/test_eks.py
@@ -345,8 +345,10 @@ def test_eks_addon_lifecycle(eks):
eks.describe_addon(clusterName=cn, addonName="vpc-cni")
assert e.value.response["Error"]["Code"] == "ResourceNotFoundException"
finally:
- try: eks.delete_cluster(name=cn)
- except Exception: pass
+ try:
+ eks.delete_cluster(name=cn)
+ except Exception:
+ pass
def test_eks_addon_create_on_missing_cluster_404(eks):
@@ -370,8 +372,10 @@ def test_eks_addon_create_duplicate_returns_resource_in_use(eks):
eks.create_addon(clusterName=cn, addonName="vpc-cni")
assert e.value.response["Error"]["Code"] == "ResourceInUseException"
finally:
- try: eks.delete_cluster(name=cn)
- except Exception: pass
+ try:
+ eks.delete_cluster(name=cn)
+ except Exception:
+ pass
# ---------------------------------------------------------------------------
@@ -397,8 +401,10 @@ def test_eks_associate_encryption_config(eks):
desc = eks.describe_cluster(name=cn)["cluster"]
assert desc["encryptionConfig"][0]["provider"]["keyArn"] == key_arn
finally:
- try: eks.delete_cluster(name=cn)
- except Exception: pass
+ try:
+ eks.delete_cluster(name=cn)
+ except Exception:
+ pass
def test_eks_associate_encryption_config_missing_cluster(eks):
@@ -425,8 +431,10 @@ def test_eks_associate_encryption_config_already_set(eks):
eks.associate_encryption_config(clusterName=cn, encryptionConfig=cfg)
assert e.value.response["Error"]["Code"] == "InvalidRequestException"
finally:
- try: eks.delete_cluster(name=cn)
- except Exception: pass
+ try:
+ eks.delete_cluster(name=cn)
+ except Exception:
+ pass
# ---------------------------------------------------------------------------
@@ -446,8 +454,10 @@ def test_eks_oidc_issuer_is_ministack_hosted(eks):
assert "/oidc/id/" in issuer, issuer
assert "amazonaws.com" not in issuer, issuer
finally:
- try: eks.delete_cluster(name=cn)
- except Exception: pass
+ try:
+ eks.delete_cluster(name=cn)
+ except Exception:
+ pass
def test_eks_oidc_discovery_document(eks):
@@ -471,8 +481,10 @@ def test_eks_oidc_discovery_document(eks):
assert jwks["keys"][0]["kty"] == "RSA"
assert jwks["keys"][0]["use"] == "sig"
finally:
- try: eks.delete_cluster(name=cn)
- except Exception: pass
+ try:
+ eks.delete_cluster(name=cn)
+ except Exception:
+ pass
# ---------------------------------------------------------------------------
@@ -520,8 +532,10 @@ def test_eks_access_entry_create_describe_delete(eks):
clusterName=cn, principalArn=principal)
assert e.value.response["Error"]["Code"] == "ResourceNotFoundException"
finally:
- try: eks.delete_cluster(name=cn)
- except Exception: pass
+ try:
+ eks.delete_cluster(name=cn)
+ except Exception:
+ pass
def test_eks_access_entry_create_duplicate_rejected(eks):
@@ -533,8 +547,10 @@ def test_eks_access_entry_create_duplicate_rejected(eks):
eks.create_access_entry(clusterName=cn, principalArn=principal)
assert e.value.response["Error"]["Code"] == "ResourceInUseException"
finally:
- try: eks.delete_cluster(name=cn)
- except Exception: pass
+ try:
+ eks.delete_cluster(name=cn)
+ except Exception:
+ pass
def test_eks_access_entry_create_missing_cluster(eks):
@@ -556,8 +572,10 @@ def test_eks_access_entry_list_returns_principal_arns(eks):
listed = eks.list_access_entries(clusterName=cn)["accessEntries"]
assert set(listed) == {p1, p2}
finally:
- try: eks.delete_cluster(name=cn)
- except Exception: pass
+ try:
+ eks.delete_cluster(name=cn)
+ except Exception:
+ pass
def test_eks_access_entry_update_patches_allowed_fields(eks):
@@ -575,8 +593,10 @@ def test_eks_access_entry_update_patches_allowed_fields(eks):
assert updated["kubernetesGroups"] == ["after"]
assert updated["username"] == "new"
finally:
- try: eks.delete_cluster(name=cn)
- except Exception: pass
+ try:
+ eks.delete_cluster(name=cn)
+ except Exception:
+ pass
def test_eks_associate_access_policy_full_cycle(eks):
@@ -609,8 +629,10 @@ def test_eks_associate_access_policy_full_cycle(eks):
)["associatedAccessPolicies"]
assert listed_after == []
finally:
- try: eks.delete_cluster(name=cn)
- except Exception: pass
+ try:
+ eks.delete_cluster(name=cn)
+ except Exception:
+ pass
def test_eks_associate_access_policy_namespace_scope_requires_namespaces(eks):
@@ -628,8 +650,10 @@ def test_eks_associate_access_policy_namespace_scope_requires_namespaces(eks):
)
assert e.value.response["Error"]["Code"] == "InvalidParameterException"
finally:
- try: eks.delete_cluster(name=cn)
- except Exception: pass
+ try:
+ eks.delete_cluster(name=cn)
+ except Exception:
+ pass
def test_eks_delete_access_entry_cascades_associated_policies(eks):
@@ -652,8 +676,10 @@ def test_eks_delete_access_entry_cascades_associated_policies(eks):
)["associatedAccessPolicies"]
assert listed == []
finally:
- try: eks.delete_cluster(name=cn)
- except Exception: pass
+ try:
+ eks.delete_cluster(name=cn)
+ except Exception:
+ pass
# ---------------------------------------------------------------------------
@@ -708,3 +734,108 @@ def test_eks_identity_provider_config(eks):
except Exception:
pass
+
+# ---------------------------------------------------------------------------
+# IdP parity: cluster status, one-per-cluster, tag wiring
+# ---------------------------------------------------------------------------
+
+def _create_cluster_for_idp(eks, name):
+ eks.create_cluster(
+ name=name,
+ roleArn="arn:aws:iam::000000000000:role/eks",
+ resourcesVpcConfig={"subnetIds": ["subnet-1"]},
+ )
+
+
+def test_associate_idp_keeps_cluster_active(eks):
+ """AssociateIdentityProviderConfigResponse is {update, tags} — cluster
+ status must stay ACTIVE; UPDATING is never observable on the cluster."""
+ cn = f"idp-status-{_uid()}"
+ _create_cluster_for_idp(eks, cn)
+ try:
+ eks.associate_identity_provider_config(
+ clusterName=cn,
+ oidc={
+ "identityProviderConfigName": "idp-1",
+ "issuerUrl": "https://example/issuer",
+ "clientId": "client-1",
+ },
+ )
+ observed = set()
+ for _ in range(5):
+ observed.add(eks.describe_cluster(name=cn)["cluster"]["status"])
+ assert "UPDATING" not in observed
+ assert observed.issubset({"CREATING", "ACTIVE"})
+ finally:
+ try:
+ eks.delete_cluster(name=cn)
+ except Exception:
+ pass
+
+
+def test_only_one_oidc_idp_per_cluster(eks):
+ """Real AWS rejects a second OIDC IdP regardless of the new name."""
+ cn = f"idp-unique-{_uid()}"
+ _create_cluster_for_idp(eks, cn)
+ try:
+ eks.associate_identity_provider_config(
+ clusterName=cn,
+ oidc={
+ "identityProviderConfigName": "primary",
+ "issuerUrl": "https://example/issuer",
+ "clientId": "client-1",
+ },
+ )
+ with pytest.raises(ClientError) as exc:
+ eks.associate_identity_provider_config(
+ clusterName=cn,
+ oidc={
+ "identityProviderConfigName": "secondary",
+ "issuerUrl": "https://example/issuer2",
+ "clientId": "client-2",
+ },
+ )
+ assert exc.value.response["Error"]["Code"] == "ResourceInUseException"
+ finally:
+ try:
+ eks.delete_cluster(name=cn)
+ except Exception:
+ pass
+
+
+def test_idp_tags_returned_by_list_tags_for_resource(eks):
+ """Tags set at associate time must be reachable via list_tags_for_resource
+ on the identityProviderConfigArn, and must clear after disassociate."""
+ cn = f"idp-tags-{_uid()}"
+ _create_cluster_for_idp(eks, cn)
+ try:
+ eks.associate_identity_provider_config(
+ clusterName=cn,
+ oidc={
+ "identityProviderConfigName": "tag-idp",
+ "issuerUrl": "https://example/issuer",
+ "clientId": "client-1",
+ },
+ tags={"env": "test", "owner": "platform"},
+ )
+ desc = eks.describe_identity_provider_config(
+ clusterName=cn,
+ identityProviderConfig={"type": "oidc", "name": "tag-idp"},
+ )
+ arn = desc["identityProviderConfig"]["oidc"]["identityProviderConfigArn"]
+ assert arn
+
+ tags = eks.list_tags_for_resource(resourceArn=arn)["tags"]
+ assert tags == {"env": "test", "owner": "platform"}
+
+ eks.disassociate_identity_provider_config(
+ clusterName=cn,
+ identityProviderConfig={"type": "oidc", "name": "tag-idp"},
+ )
+ tags_after = eks.list_tags_for_resource(resourceArn=arn)["tags"]
+ assert tags_after == {}
+ finally:
+ try:
+ eks.delete_cluster(name=cn)
+ except Exception:
+ pass