Skip to content

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

feat(ec2,eks): Fleet capacity + OIDC identity provider config (#794)

Rajesh BAVANANTHAM10f678f197db
diff --git a/ministack/services/ec2.py b/ministack/services/ec2.py
index 149f4f5d..ae1b58a3 100644
--- a/ministack/services/ec2.py
+++ b/ministack/services/ec2.py
@@ -103,6 +103,8 @@ _vpn_gateways = AccountScopedDict() # vgw_id -> VPN gateway record
_customer_gateways = AccountScopedDict() # cgw_id -> customer gateway record
_vpn_connections = AccountScopedDict() # vpn_id -> VPN connection record
_launch_templates = AccountScopedDict() # lt_id -> launch template record (includes versions list)
+_fleets = AccountScopedDict() # fleet_id -> fleet record
+
# ── Persistence ────────────────────────────────────────────
@@ -133,6 +135,7 @@ def get_state():
"customer_gateways": copy.deepcopy(_customer_gateways),
"vpn_connections": copy.deepcopy(_vpn_connections),
"launch_templates": copy.deepcopy(_launch_templates),
+ "fleets": copy.deepcopy(_fleets),
}
@@ -162,6 +165,7 @@ def restore_state(data):
_customer_gateways.update(data.get("customer_gateways", {}))
_vpn_connections.update(data.get("vpn_connections", {}))
_launch_templates.update(data.get("launch_templates", {}))
+ _fleets.update(data.get("fleets", {}))
try:
@@ -295,38 +299,12 @@ async def handle_request(method, path, headers, body, query_params):
# Instances
# ---------------------------------------------------------------------------
-def _run_instances(p):
- image_id = _p(p, "ImageId") or "ami-00000000"
- instance_type = _p(p, "InstanceType") or "t2.micro"
- min_count = int(_p(p, "MinCount") or "1")
- max_count = int(_p(p, "MaxCount") or "1")
- if min_count > max_count:
- return _error("InvalidParameterCombination",
- f"Value ({min_count}) for parameter MinCount is not valid. "
- f"MinCount must not exceed MaxCount.", 400)
- key_name = _p(p, "KeyName") or ""
- subnet_id = _p(p, "SubnetId") or _DEFAULT_SUBNET_ID
- user_data = _p(p, "UserData") or ""
-
- sg_ids = _parse_member_list(p, "SecurityGroupId")
+def _launch_instances_internal(image_id, instance_type, subnet_id, count, key_name="", user_data="", sg_ids=None, requested_private_ip=None, iam_profile=None):
+ now = _now_ts()
if not sg_ids:
sg_ids = [_DEFAULT_SG_ID]
-
- now = _now_ts()
- # Optional caller-provided values: respect them if set; fall back to defaults otherwise.
- requested_private_ip = _p(p, "PrivateIpAddress")
- iam_arn = _p(p, "IamInstanceProfile.Arn")
- iam_name = _p(p, "IamInstanceProfile.Name")
- iam_profile = None
- if iam_arn or iam_name:
- # Real AWS returns both Arn and Id. We synthesize a stable Id from the
- # name/arn so DescribeInstances reads back as it does on AWS.
- 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}
created = []
- for _ in range(max(1, min(min_count, max_count))):
+ for _ in range(count):
instance_id = _new_instance_id()
private_ip = requested_private_ip or _random_ip("10.0.")
# Synthesize a real root EBS volume so DescribeVolumes / DescribeInstances
@@ -366,7 +344,7 @@ def _run_instances(p):
"DeleteOnTermination": True,
},
}]
- _instances[instance_id] = {
+ inst = {
"InstanceId": instance_id,
"ImageId": image_id,
"InstanceType": instance_type,
@@ -398,7 +376,52 @@ def _run_instances(p):
"BlockDeviceMappings": block_device_mappings,
"IamInstanceProfile": iam_profile,
}
- created.append(_instances[instance_id])
+ _instances[instance_id] = inst
+ created.append(inst)
+ return created
+
+
+def _run_instances(p):
+ image_id = _p(p, "ImageId") or "ami-00000000"
+ instance_type = _p(p, "InstanceType") or "t2.micro"
+ min_count = int(_p(p, "MinCount") or "1")
+ max_count = int(_p(p, "MaxCount") or "1")
+ if min_count > max_count:
+ return _error("InvalidParameterCombination",
+ f"Value ({min_count}) for parameter MinCount is not valid. "
+ f"MinCount must not exceed MaxCount.", 400)
+ key_name = _p(p, "KeyName") or ""
+ subnet_id = _p(p, "SubnetId") or _DEFAULT_SUBNET_ID
+ user_data = _p(p, "UserData") or ""
+
+ sg_ids = _parse_member_list(p, "SecurityGroupId")
+ if not sg_ids:
+ sg_ids = [_DEFAULT_SG_ID]
+
+ # Optional caller-provided values: respect them if set; fall back to defaults otherwise.
+ requested_private_ip = _p(p, "PrivateIpAddress")
+ iam_arn = _p(p, "IamInstanceProfile.Arn")
+ iam_name = _p(p, "IamInstanceProfile.Name")
+ iam_profile = None
+ if iam_arn or iam_name:
+ # Real AWS returns both Arn and Id. We synthesize a stable Id from the
+ # name/arn so DescribeInstances reads back as it does on AWS.
+ 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}
+
+ created = _launch_instances_internal(
+ image_id=image_id,
+ instance_type=instance_type,
+ subnet_id=subnet_id,
+ count=max(1, min(min_count, max_count)),
+ key_name=key_name,
+ user_data=user_data,
+ sg_ids=sg_ids,
+ requested_private_ip=requested_private_ip,
+ iam_profile=iam_profile
+ )
# Process TagSpecifications
i = 1
@@ -425,6 +448,7 @@ def _run_instances(p):
return _xml(200, "RunInstancesResponse", inner)
+
_last_cleanup = [0.0]
def _cleanup_terminated():
@@ -3926,6 +3950,7 @@ def reset():
_customer_gateways.clear()
_vpn_connections.clear()
_launch_templates.clear()
+ _fleets.clear()
_init_defaults()
@@ -4658,8 +4683,272 @@ def _delete_launch_template(p):
</launchTemplate>""")
+def _fleet_instances_xml(instances_list, configs):
+ 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"""
+ <launchTemplateAndOverrides>
+ <launchTemplateSpecification>
+ <launchTemplateId>{_esc(lt_id_val)}</launchTemplateId>
+ <launchTemplateName>{_esc(lt_name_val)}</launchTemplateName>
+ <version>{_esc(version_val)}</version>
+ </launchTemplateSpecification>
+ </launchTemplateAndOverrides>
+ """
+ instances_xml.append(f"""<item>
+ {lt_and_overrides_xml}
+ <lifecycle>{_esc(item["Lifecycle"])}</lifecycle>
+ <instanceIds>{inst_ids_xml}</instanceIds>
+ <instanceType>{_esc(item["InstanceType"])}</instanceType>
+ </item>""")
+ return "".join(instances_xml)
+
+
+def _create_fleet(p):
+ fleet_type = _p(p, "Type") or "maintain"
+ total_capacity = int(
+ _p(p, "TargetCapacitySpecification.TotalTargetCapacity")
+ or _p(p, "TargetCapacitySpecification.OnDemandTargetCapacity")
+ or _p(p, "TargetCapacitySpecification.SpotTargetCapacity")
+ or "1"
+ )
+
+ # Parse LaunchTemplateConfigs
+ configs = []
+ i = 1
+ while True:
+ lt_id = _p(p, f"LaunchTemplateConfigs.{i}.LaunchTemplateSpecification.LaunchTemplateId")
+ lt_name = _p(p, f"LaunchTemplateConfigs.{i}.LaunchTemplateSpecification.LaunchTemplateName")
+ version = _p(p, f"LaunchTemplateConfigs.{i}.LaunchTemplateSpecification.Version")
+
+ # Overrides
+ overrides = []
+ j = 1
+ while True:
+ itype = _p(p, f"LaunchTemplateConfigs.{i}.Overrides.{j}.InstanceType")
+ sub_id = _p(p, f"LaunchTemplateConfigs.{i}.Overrides.{j}.SubnetId")
+ if not itype and not sub_id:
+ break
+ overrides.append({
+ "InstanceType": itype,
+ "SubnetId": sub_id
+ })
+ j += 1
+
+ if not lt_id and not lt_name and not overrides:
+ break
+
+ configs.append({
+ "LaunchTemplateSpecification": {
+ "LaunchTemplateId": lt_id,
+ "LaunchTemplateName": lt_name,
+ "Version": version or "$Default",
+ },
+ "Overrides": overrides,
+ })
+ 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]
+ 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
+ )
+
+ 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,
+ )
+
+ # Process tag specifications
+ 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[:]
+
+ fleet_id = "fleet-" + new_uuid()
+ if fleet_tags:
+ _tags[fleet_id] = fleet_tags
+
+ now_iso = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
+ fleet_record = {
+ "FleetId": fleet_id,
+ "FleetState": "active",
+ "ActivityStatus": "fulfilled",
+ "CreateTime": now_iso,
+ "Type": fleet_type,
+ "FulfilledCapacity": float(total_capacity),
+ "FulfilledOnDemandCapacity": float(total_capacity) if fleet_type != "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",
+ },
+ "LaunchTemplateConfigs": configs,
+ "Instances": [
+ {
+ "InstanceIds": [inst["InstanceId"] for inst in launched],
+ "InstanceType": instance_type,
+ "Lifecycle": "on-demand" if fleet_type != "spot" else "spot",
+ }
+ ],
+ "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)
+
+
+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)
+
+ items = []
+ for f in results:
+ instances_xml_str = _fleet_instances_xml(f["Instances"], f["LaunchTemplateConfigs"])
+ tag_set_xml = _tag_set_xml(f["FleetId"])
+ tcs = f["TargetCapacitySpecification"]
+ items.append(f"""<item>
+ <activityStatus>{_esc(f['ActivityStatus'])}</activityStatus>
+ <createTime>{_esc(f['CreateTime'])}</createTime>
+ <fleetId>{_esc(f['FleetId'])}</fleetId>
+ <fleetState>{_esc(f['FleetState'])}</fleetState>
+ <fulfilledCapacity>{f['FulfilledCapacity']}</fulfilledCapacity>
+ <fulfilledOnDemandCapacity>{f['FulfilledOnDemandCapacity']}</fulfilledOnDemandCapacity>
+ <targetCapacitySpecification>
+ <totalTargetCapacity>{int(tcs['TotalTargetCapacity'])}</totalTargetCapacity>
+ <onDemandTargetCapacity>{int(tcs['OnDemandTargetCapacity'])}</onDemandTargetCapacity>
+ <spotTargetCapacity>{int(tcs['SpotTargetCapacity'])}</spotTargetCapacity>
+ <defaultTargetCapacityType>{_esc(tcs['DefaultTargetCapacityType'])}</defaultTargetCapacityType>
+ </targetCapacitySpecification>
+ <type>{_esc(f['Type'])}</type>
+ <fleetInstanceSet>{instances_xml_str}</fleetInstanceSet>
+ <errorSet/>
+ {tag_set_xml}
+ </item>""")
+
+ fleet_set_xml = "".join(items)
+ return _xml(200, "DescribeFleetsResponse", f"<fleetSet>{fleet_set_xml}</fleetSet>")
+
+
_ACTION_MAP = {
"RunInstances": _run_instances,
+
"DescribeInstances": _describe_instances,
"DescribeInstanceStatus": _describe_instance_status,
"DescribeInstanceAttribute": _describe_instance_attribute,
@@ -4813,4 +5102,6 @@ _ACTION_MAP = {
"DescribeLaunchTemplateVersions": _describe_launch_template_versions,
"ModifyLaunchTemplate": _modify_launch_template,
"DeleteLaunchTemplate": _delete_launch_template,
+ "CreateFleet": _create_fleet,
+ "DescribeFleets": _describe_fleets,
}
diff --git a/ministack/services/eks.py b/ministack/services/eks.py
index c34c7bb1..6e02b0ef 100644
--- a/ministack/services/eks.py
+++ b/ministack/services/eks.py
@@ -57,6 +57,7 @@ _addons = AccountScopedDict() # "cluster/addonName" -> addon record
_access_entries = AccountScopedDict() # "cluster\x00principalArn" -> access entry record
_access_policies = AccountScopedDict()# "cluster\x00principalArn\x00policyArn" -> associated policy
_tags = AccountScopedDict() # arn -> {key: value}
+_idp_configs = AccountScopedDict() # "cluster\x00idp_name" -> idp record
_port_counter_lock = threading.Lock()
_port_counter = [EKS_BASE_PORT]
_oidc_keypair_lock = threading.Lock()
@@ -115,6 +116,7 @@ def reset():
_access_entries.clear()
_access_policies.clear()
_tags.clear()
+ _idp_configs.clear()
_port_counter[0] = EKS_BASE_PORT
_stop_all_k3s()
@@ -135,6 +137,7 @@ def get_state():
"access_entries": copy.deepcopy(_access_entries),
"access_policies": copy.deepcopy(_access_policies),
"tags": copy.deepcopy(_tags),
+ "idp_configs": copy.deepcopy(_idp_configs),
"port_counter": _port_counter[0],
}
@@ -146,6 +149,7 @@ def restore_state(data):
_access_entries.update(data.get("access_entries", {}))
_access_policies.update(data.get("access_policies", {}))
_tags.update(data.get("tags", {}))
+ _idp_configs.update(data.get("idp_configs", {}))
if "port_counter" in data:
_port_counter[0] = data["port_counter"]
# Restored clusters have no running k3s container — keep ACTIVE with mock endpoint
@@ -158,6 +162,7 @@ def restore_state(data):
c["_docker_id"] = None
+
try:
_restored = load_state("eks")
if _restored:
@@ -254,7 +259,33 @@ def _wait_for_port(host, port, timeout=30):
return False
-def _k3s_run_kwargs(name: str, port: int, ms_network: str | None = None) -> dict:
+def _collect_oidc_state(cluster_name: str):
+ """Return (apiserver_args, cfg_refs) for OIDC configs on a cluster.
+
+ MUST be called from a request context (uses contextvars via AccountScopedDict).
+ Returned cfg_refs are live dict references — background threads can mutate
+ their "status" field without re-entering the request scope.
+ """
+ args: list[str] = []
+ cfg_refs: list[dict] = []
+ for key, cfg in list(_idp_configs.items()):
+ cn, _, _ = key.partition("\x00")
+ if cn != cluster_name:
+ continue
+ cfg_refs.append(cfg)
+ oidc = cfg.get("oidc", {})
+ if not oidc:
+ continue
+ args.append(f"--kube-apiserver-arg=oidc-issuer-url={oidc.get('issuerUrl')}")
+ args.append(f"--kube-apiserver-arg=oidc-client-id={oidc.get('clientId')}")
+ if oidc.get("usernameClaim"):
+ args.append(f"--kube-apiserver-arg=oidc-username-claim={oidc.get('usernameClaim')}")
+ if oidc.get("groupsClaim"):
+ args.append(f"--kube-apiserver-arg=oidc-groups-claim={oidc.get('groupsClaim')}")
+ return args, cfg_refs
+
+
+def _k3s_run_kwargs(name: str, port: int, ms_network: str | None = None, oidc_args: list[str] | None = None) -> dict:
"""Build the docker run kwargs for a k3s server container.
`privileged=True` is required: k3s server mode remounts `/sys/fs/cgroup`,
@@ -264,12 +295,18 @@ def _k3s_run_kwargs(name: str, port: int, ms_network: str | None = None) -> dict
list and unconfined security_opt are kept as defence-in-depth so that
hardened Docker setups still get the right capability set.
"""
+ command = [
+ "server",
+ "--disable=traefik,metrics-server,servicelb",
+ "--tls-san=0.0.0.0",
+ "--https-listen-port=6443",
+ ]
+ if oidc_args:
+ command.extend(oidc_args)
+
run_kwargs = dict(
image=apply_image_prefix(EKS_K3S_IMAGE),
- command=["server",
- "--disable=traefik,metrics-server,servicelb",
- "--tls-san=0.0.0.0",
- "--https-listen-port=6443"],
+ command=command,
detach=True,
privileged=True,
cap_add=[
@@ -291,6 +328,7 @@ def _k3s_run_kwargs(name: str, port: int, ms_network: str | None = None) -> dict
)
if ms_network:
run_kwargs["network"] = ms_network
+
return run_kwargs
@@ -389,6 +427,8 @@ def _create_cluster(body):
if cluster["tags"]:
_tags[arn] = dict(cluster["tags"])
+ oidc_args, _idp_cfg_refs = _collect_oidc_state(name)
+
def _bg_start():
client = _get_docker()
if not client:
@@ -397,7 +437,8 @@ def _create_cluster(body):
return
try:
ms_network = _get_ministack_network(client)
- run_kwargs = _k3s_run_kwargs(name=name, port=port, ms_network=ms_network)
+ run_kwargs = _k3s_run_kwargs(name=name, port=port, ms_network=ms_network, oidc_args=oidc_args)
+
container = client.containers.run(**run_kwargs)
cluster["_docker_id"] = container.id
@@ -858,10 +899,194 @@ def _associate_encryption_config(cluster_name, body):
return _json_resp(200, {"update": update})
+# ---------------------------------------------------------------------------
+# OIDC Identity Provider Config (AssociateIdentityProviderConfig)
+# ---------------------------------------------------------------------------
+
+def _restart_k3s(cluster_name, oidc_args=None, idp_cfg_refs=None):
+ """Restart the cluster's k3s container with the supplied OIDC args.
+
+ Both ``oidc_args`` and ``idp_cfg_refs`` must be captured by the CALLER
+ inside the request context (where AccountScopedDict can resolve the
+ account). The background thread closes over them so it never needs the
+ request's contextvars.
+ """
+ cluster = _clusters.get(cluster_name)
+ if not cluster:
+ return
+ client = _get_docker()
+ if not client:
+ return
+
+ cluster["status"] = "UPDATING"
+ oidc_args = oidc_args or []
+ idp_cfg_refs = idp_cfg_refs or []
+
+ def _mark_idp_active():
+ for cfg in idp_cfg_refs:
+ cfg["status"] = "ACTIVE"
+
+ def _bg_restart():
+ port = cluster["_port"]
+ try:
+ docker_id = cluster.get("_docker_id")
+ if docker_id:
+ try:
+ container = client.containers.get(docker_id)
+ container.stop(timeout=5)
+ container.remove(v=True, force=True)
+ except Exception:
+ pass
+ cluster["_docker_id"] = None
+
+ ms_network = _get_ministack_network(client)
+ run_kwargs = _k3s_run_kwargs(name=cluster_name, port=port, ms_network=ms_network, oidc_args=oidc_args)
+
+ container = client.containers.run(**run_kwargs)
+ cluster["_docker_id"] = container.id
+
+ ep = ""
+ if ms_network:
+ container.reload()
+ networks = container.attrs.get("NetworkSettings", {}).get("Networks", {})
+ container_ip = networks.get(ms_network, {}).get("IPAddress", "")
+ if container_ip and _wait_for_port(container_ip, 6443):
+ ep = f"https://{container_ip}:6443"
+ logger.info("EKS: k3s for %s restarted and ready at %s (network %s)", cluster_name, ep, ms_network)
+ if not ep:
+ if _wait_for_port("127.0.0.1", port):
+ ep = f"https://localhost:{port}"
+ logger.info("EKS: k3s for %s restarted and ready at %s", cluster_name, ep)
+ else:
+ logger.warning("EKS: k3s for %s restarted but did not become ready on port %d", cluster_name, port)
+ ep = f"https://localhost:{port}"
+
+ 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()
+
+ threading.Thread(target=_bg_restart, daemon=True, name=f"eks-restart-{cluster_name}").start()
+
+
+def _associate_identity_provider_config(cluster_name, body):
+ cluster = _clusters.get(cluster_name)
+ if not cluster:
+ return _error(404, "ResourceNotFoundException", f"No cluster found for name: {cluster_name}.")
+
+ oidc = body.get("oidc")
+ if not oidc:
+ return _error(400, "InvalidParameterException", "oidc configuration is required.")
+
+ idp_name = oidc.get("identityProviderConfigName")
+ if not idp_name:
+ return _error(400, "InvalidParameterException", "identityProviderConfigName is required inside oidc config.")
+
+ if not oidc.get("issuerUrl") or not oidc.get("clientId"):
+ return _error(400, "InvalidParameterException", "issuerUrl and clientId are required inside oidc config.")
+
+ 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()}"
+ )
+ _idp_configs[key] = {
+ "oidc": oidc,
+ "status": "CREATING",
+ "tags": body.get("tags") or {},
+ "arn": arn,
+ }
+
+ oidc_args, idp_cfg_refs = _collect_oidc_state(cluster_name)
+ _restart_k3s(cluster_name, oidc_args=oidc_args, idp_cfg_refs=idp_cfg_refs)
+
+ update = {
+ "id": new_uuid(),
+ "status": "InProgress",
+ "type": "IdentityProviderConfigUpdate",
+ "params": [{"type": "IdentityProviderConfig", "value": idp_name}],
+ "createdAt": _now(),
+ "errors": [],
+ }
+ return _json_resp(200, {"update": update, "tags": body.get("tags") or {}})
+
+
+def _describe_identity_provider_config(cluster_name, body):
+ idp_cfg = body.get("identityProviderConfig") or {}
+ name = idp_cfg.get("name")
+ if not name:
+ return _error(400, "InvalidParameterException", "name is required in identityProviderConfig.")
+
+ key = f"{cluster_name}\x00{name}"
+ cfg = _idp_configs.get(key)
+ if not cfg:
+ return _error(404, "ResourceNotFoundException", f"OIDC provider configuration '{name}' not found on cluster '{cluster_name}'.")
+
+ oidc = cfg["oidc"]
+ response = {
+ "identityProviderConfig": {
+ "oidc": {
+ "clientId": oidc.get("clientId"),
+ "clusterName": cluster_name,
+ "groupsClaim": oidc.get("groupsClaim"),
+ "groupsPrefix": oidc.get("groupsPrefix"),
+ "identityProviderConfigArn": cfg.get("arn", ""),
+ "identityProviderConfigName": name,
+ "issuerUrl": oidc.get("issuerUrl"),
+ "requiredClaims": oidc.get("requiredClaims") or {},
+ "status": cfg.get("status", "ACTIVE"),
+ "tags": cfg.get("tags") or {},
+ "usernameClaim": oidc.get("usernameClaim"),
+ "usernamePrefix": oidc.get("usernamePrefix"),
+ }
+ }
+ }
+ return _json_resp(200, response)
+
+
+def _disassociate_identity_provider_config(cluster_name, body):
+ cluster = _clusters.get(cluster_name)
+ if not cluster:
+ return _error(404, "ResourceNotFoundException", f"No cluster found for name: {cluster_name}.")
+
+ idp_cfg = body.get("identityProviderConfig") or {}
+ name = idp_cfg.get("name")
+ if not name:
+ return _error(400, "InvalidParameterException", "name is required in identityProviderConfig.")
+
+ key = f"{cluster_name}\x00{name}"
+ 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)
+ oidc_args, idp_cfg_refs = _collect_oidc_state(cluster_name)
+ _restart_k3s(cluster_name, oidc_args=oidc_args, idp_cfg_refs=idp_cfg_refs)
+
+ update = {
+ "id": new_uuid(),
+ "status": "InProgress",
+ "type": "IdentityProviderConfigUpdate",
+ "params": [{"type": "IdentityProviderConfig", "value": name}],
+ "createdAt": _now(),
+ "errors": [],
+ }
+ return _json_resp(200, {"update": update})
+
+
# ---------------------------------------------------------------------------
# OIDC discovery / JWKS (IRSA support)
# ---------------------------------------------------------------------------
+
def _oidc_discovery(oidc_id):
issuer = _issuer_url(oidc_id)
return _json_resp(200, {
@@ -977,6 +1202,28 @@ async def handle_request(method, path, headers, body_bytes, query_params):
if method == "POST":
return _associate_encryption_config(cluster_name, body)
+ # POST /clusters/{name}/identity-provider-configs/associate
+ m = re.fullmatch(r"/clusters/([A-Za-z0-9_-]+)/identity-provider-configs/associate", path)
+ if m:
+ cluster_name = m.group(1)
+ if method == "POST":
+ return _associate_identity_provider_config(cluster_name, body)
+
+ # POST /clusters/{name}/identity-provider-configs/disassociate
+ m = re.fullmatch(r"/clusters/([A-Za-z0-9_-]+)/identity-provider-configs/disassociate", path)
+ if m:
+ cluster_name = m.group(1)
+ if method == "POST":
+ return _disassociate_identity_provider_config(cluster_name, body)
+
+ # POST /clusters/{name}/identity-provider-configs/describe
+ m = re.fullmatch(r"/clusters/([A-Za-z0-9_-]+)/identity-provider-configs/describe", path)
+ if m:
+ cluster_name = m.group(1)
+ if method == "POST":
+ return _describe_identity_provider_config(cluster_name, body)
+
+
# OIDC discovery + JWKS (IRSA). Path matches AWS shape under the ministack
# /oidc prefix because we can't own oidc.eks.{region}.amazonaws.com.
m = re.fullmatch(r"/oidc/id/([A-Z0-9]+)/\.well-known/openid-configuration", path)
diff --git a/tests/test_ec2.py b/tests/test_ec2.py
index 1fd5726b..e37b473e 100644
--- a/tests/test_ec2.py
+++ b/tests/test_ec2.py
@@ -2117,3 +2117,70 @@ def test_ebs_modify_volume_attribute(ec2):
# Stub — just verify it doesn't error
resp = ec2.describe_volume_attribute(VolumeId=vol_id, Attribute="autoEnableIO")
assert resp["VolumeId"] == vol_id
+
+
+def test_ec2_create_describe_fleet(ec2):
+ lt = ec2.create_launch_template(
+ LaunchTemplateName="test-fleet-lt",
+ LaunchTemplateData={"ImageId": "ami-12345678", "InstanceType": "t2.small"}
+ )
+ lt_id = lt["LaunchTemplate"]["LaunchTemplateId"]
+
+ # Create fleet with overrides and tag specifications
+ fleet = ec2.create_fleet(
+ LaunchTemplateConfigs=[
+ {
+ "LaunchTemplateSpecification": {
+ "LaunchTemplateId": lt_id,
+ "Version": "1"
+ },
+ "Overrides": [
+ {
+ "InstanceType": "t2.medium"
+ }
+ ]
+ }
+ ],
+ TargetCapacitySpecification={
+ "TotalTargetCapacity": 2,
+ "OnDemandTargetCapacity": 2,
+ },
+ Type="instant",
+ TagSpecifications=[
+ {
+ "ResourceType": "fleet",
+ "Tags": [
+ {"Key": "Environment", "Value": "Production"}
+ ]
+ }
+ ]
+ )
+
+ fleet_id = fleet["FleetId"]
+ assert fleet_id.startswith("fleet-")
+ assert len(fleet["Instances"]) == 1
+ assert fleet["Instances"][0]["InstanceType"] == "t2.medium"
+ assert fleet["Instances"][0]["Lifecycle"] == "on-demand"
+ assert len(fleet["Instances"][0]["InstanceIds"]) == 2
+
+ # Verify instances are running
+ inst_ids = fleet["Instances"][0]["InstanceIds"]
+ desc_inst = ec2.describe_instances(InstanceIds=inst_ids)
+ reservations = desc_inst["Reservations"]
+ assert len(reservations) >= 1
+ launched_instances = [inst for r in reservations for inst in r["Instances"]]
+ assert len(launched_instances) == 2
+ for inst in launched_instances:
+ assert inst["InstanceType"] == "t2.medium"
+ assert inst["ImageId"] == "ami-12345678"
+
+ # Describe fleet and verify details and tags
+ resp = ec2.describe_fleets(FleetIds=[fleet_id])
+ assert len(resp["Fleets"]) == 1
+ f = resp["Fleets"][0]
+ assert f["FleetId"] == fleet_id
+ assert f["FulfilledCapacity"] == 2.0
+ assert f["FulfilledOnDemandCapacity"] == 2.0
+ assert f["TargetCapacitySpecification"]["TotalTargetCapacity"] == 2
+ assert any(t["Key"] == "Environment" and t["Value"] == "Production" for t in f.get("Tags", []))
+
diff --git a/tests/test_eks.py b/tests/test_eks.py
index 20f3362f..180f9bf3 100644
--- a/tests/test_eks.py
+++ b/tests/test_eks.py
@@ -654,3 +654,57 @@ def test_eks_delete_access_entry_cascades_associated_policies(eks):
finally:
try: eks.delete_cluster(name=cn)
except Exception: pass
+
+
+# ---------------------------------------------------------------------------
+# AssociateIdentityProviderConfig
+# ---------------------------------------------------------------------------
+
+def test_eks_identity_provider_config(eks):
+ cn = f"idp-{_uid()}"
+ eks.create_cluster(
+ name=cn, roleArn="arn:aws:iam::000000000000:role/eks",
+ resourcesVpcConfig={"subnetIds": ["subnet-1"]},
+ )
+ try:
+ # 1. Associate OIDC config
+ resp = eks.associate_identity_provider_config(
+ clusterName=cn,
+ oidc={
+ "identityProviderConfigName": "cognito-idp",
+ "issuerUrl": "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_000000000",
+ "clientId": "client-12345",
+ "usernameClaim": "sub",
+ "groupsClaim": "cognito:groups",
+ },
+ tags={"env": "test"}
+ )
+ upd = resp["update"]
+ assert upd["type"] == "IdentityProviderConfigUpdate"
+ assert upd["status"] in ("InProgress", "Successful")
+
+ # 2. Describe OIDC config
+ desc = eks.describe_identity_provider_config(
+ clusterName=cn,
+ identityProviderConfig={"type": "oidc", "name": "cognito-idp"}
+ )
+ oidc_desc = desc["identityProviderConfig"]["oidc"]
+ assert oidc_desc["identityProviderConfigName"] == "cognito-idp"
+ assert oidc_desc["clientId"] == "client-12345"
+ assert oidc_desc["issuerUrl"] == "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_000000000"
+ assert oidc_desc["status"] in ("CREATING", "ACTIVE")
+
+ # 3. Disassociate OIDC config
+ dis_resp = eks.disassociate_identity_provider_config(
+ clusterName=cn,
+ identityProviderConfig={"type": "oidc", "name": "cognito-idp"}
+ )
+ dis_upd = dis_resp["update"]
+ assert dis_upd["type"] == "IdentityProviderConfigUpdate"
+
+ finally:
+ try:
+ eks.delete_cluster(name=cn)
+ except Exception:
+ pass
+