Skip to content

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

feat: EC2 emulation + SFN Activities, 644 tests (v1.1.1) (#20)

Nahuel Nucerac335382d242a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ec07d24a..23a3c2a9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,40 @@ Versioning follows [Semantic Versioning](https://semver.org/).
---
+## [1.1.1] — 2026-03-29
+
+### Added
+- **Amazon EC2** (`ministack/services/ec2.py`) — full API-level emulation (no real VMs)
+ - **Instances**: `RunInstances`, `DescribeInstances`, `TerminateInstances`, `StopInstances`, `StartInstances`, `RebootInstances`
+ - **Images**: `DescribeImages` — returns 3 stub AMIs (Amazon Linux 2, Ubuntu 22.04, Windows Server 2022)
+ - **Security Groups**: `CreateSecurityGroup`, `DeleteSecurityGroup`, `DescribeSecurityGroups`, `AuthorizeSecurityGroupIngress`, `RevokeSecurityGroupIngress`, `AuthorizeSecurityGroupEgress`, `RevokeSecurityGroupEgress`
+ - **Key Pairs**: `CreateKeyPair`, `DeleteKeyPair`, `DescribeKeyPairs`, `ImportKeyPair`
+ - **VPC**: `CreateVpc`, `DeleteVpc`, `DescribeVpcs`, `ModifyVpcAttribute` — default VPC pre-created
+ - **Subnets**: `CreateSubnet`, `DeleteSubnet`, `DescribeSubnets`, `ModifySubnetAttribute` — default subnet pre-created
+ - **Internet Gateways**: `CreateInternetGateway`, `DeleteInternetGateway`, `DescribeInternetGateways`, `AttachInternetGateway`, `DetachInternetGateway`
+ - **Route Tables**: `CreateRouteTable`, `DeleteRouteTable`, `DescribeRouteTables`, `AssociateRouteTable`, `DisassociateRouteTable`, `CreateRoute`, `ReplaceRoute`, `DeleteRoute` — default route table pre-created for default VPC
+ - **Network Interfaces (ENI)**: `CreateNetworkInterface`, `DeleteNetworkInterface`, `DescribeNetworkInterfaces`, `AttachNetworkInterface`, `DetachNetworkInterface` — full botocore-compliant response shape (`availabilityZone`, `sourceDestCheck`, `interfaceType`, `privateIpAddressesSet`)
+ - **VPC Endpoints**: `CreateVpcEndpoint`, `DeleteVpcEndpoints`, `DescribeVpcEndpoints` — Gateway and Interface types; `routeTableIdSet` / `subnetIdSet` serialized correctly
+ - **Availability Zones**: `DescribeAvailabilityZones`
+ - **Elastic IPs**: `AllocateAddress`, `ReleaseAddress`, `AssociateAddress`, `DisassociateAddress`, `DescribeAddresses`
+ - **Tags**: `CreateTags`, `DeleteTags`, `DescribeTags`
+ - Default VPC, subnet, security group, internet gateway, and route table always present
+ - Rules stored but not enforced (matches LocalStack behaviour)
+ - 26 integration tests
+- **Step Functions Activities** — full worker-based activity task pattern
+ - `CreateActivity`, `DeleteActivity`, `DescribeActivity`, `ListActivities` — full CRUD
+ - `GetActivityTask` — async long-poll (up to 60 s) returning `taskToken` + `input` to worker; non-blocking (uses `asyncio.sleep` — does not stall the event loop)
+ - Activity Task state execution — when a Task state's `Resource` is an activity ARN, the execution enqueues the task and waits for a worker to call `SendTaskSuccess` or `SendTaskFailure`
+ - `ActivityAlreadyExists` raised on duplicate `CreateActivity` (matches AWS behaviour — not idempotent)
+ - `ActivityDoesNotExist` raised on `DeleteActivity`, `DescribeActivity`, `GetActivityTask` for unknown ARN
+ - Activity ARN format: `arn:aws:states:{region}:{account}:activity:{name}`
+ - 5 integration tests: CRUD, list, duplicate-name error, worker success flow, worker failure flow
+
+### Tests
+- 644 integration tests — all passing
+
+---
+
## [1.1.0] — 2026-03-28
### Added
@@ -51,7 +85,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- Fixed `test_apigwv1_usage_plan_key_crud`: `Name`/`Enabled` → `name`/`enabled` (boto3 lowercase params)
- Fixed `test_lambda_reset_terminates_workers`: timeout 5 s → 15 s with 3-attempt retry
- Fixed `test_rds_snapshot_crud` / `test_rds_deletion_protection`: added `finally` cleanup so RDS containers are deleted after each test
-- 613 integration tests — all passing against Docker image
+- 613 integration tests — all passing against Docker image (618 as of v1.1.1)
---
@@ -325,6 +359,6 @@ Initial public release. Built as a free, open-source alternative to LocalStack.
## Roadmap
### Planned
-- Cognito (user pools, sign-up/sign-in)
- ACM (certificate management)
+- State persistence for Secrets Manager, SSM, DynamoDB (`PERSIST_STATE=1` currently only covers API Gateway v1/v2)
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index aaef2381..41631be3 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -83,7 +83,7 @@ def reset():
**Protocol guide:**
- JSON services (DynamoDB, SecretsManager, Glue, Athena, Cognito, etc.) — use `json_response` / `error_response_json`, route via `X-Amz-Target`
-- XML services (S3, SQS, SNS, IAM, RDS, ElastiCache) — build XML responses, route via `Action` query param
+- XML/Query services (S3, SQS, SNS, IAM, STS, RDS, ElastiCache, EC2) — build XML responses, route via `Action` query param; use `_xml(status, root_tag, inner)` pattern; verify field names against botocore shapes via `Loader().load_service_model()`
- REST services (Lambda, ECS, Route53) — route via URL path
### 2. Register in `ministack/app.py`
@@ -171,6 +171,7 @@ pytest tests/ -v -k "cognito"
- [ ] Tests added and passing (`pytest tests/ -v`)
- [ ] Service added to the table in `README.md`
- [ ] Entry added to `CHANGELOG.md`
+- [ ] Version bumped in `pyproject.toml`
---
@@ -179,8 +180,7 @@ pytest tests/ -v -k "cognito"
High-value contributions right now:
- **ACM** — certificate provisioning and validation stubs
-- **CloudFormation** — basic stack CRUD with resource mapping to existing services
-- **More S3 operations** — object lock, replication configuration, website hosting, object tagging
+- **More S3 operations** — object lock, replication configuration, object tagging
- **Athena without DuckDB** — graceful degradation or lighter SQL engine option
- **SES v2** — `ses:SendEmail` with the v2 API shapes
- **Lambda layers** — `PublishLayerVersion`, `GetLayerVersion`, `ListLayerVersions`
diff --git a/README.md b/README.md
index a72a4777..f2f1f633 100644
--- a/README.md
+++ b/README.md
@@ -24,7 +24,7 @@
LocalStack recently moved its core services behind a paid plan. If you relied on LocalStack Community for local development and CI/CD pipelines, MiniStack is your free alternative.
-- **25 AWS services** emulated on a single port (4566)
+- **26 AWS services** emulated on a single port (4566)
- **Drop-in compatible** — works with `boto3`, AWS CLI, Terraform, CDK, Pulumi, any SDK
- **Real infrastructure** — RDS spins up actual Postgres/MySQL containers, ElastiCache spins up real Redis, Athena runs real SQL via DuckDB, ECS runs real Docker containers
- **Tiny footprint** — ~150MB image, ~30MB RAM at idle vs LocalStack's ~1GB image and ~500MB RAM
@@ -164,6 +164,33 @@ sfn.create_state_machine(
definition='{"StartAt":"Hello","States":{"Hello":{"Type":"Pass","End":true}}}',
roleArn="arn:aws:iam::000000000000:role/role",
)
+
+# EC2
+ec2 = client("ec2")
+reservation = ec2.run_instances(
+ ImageId="ami-00000001",
+ MinCount=1,
+ MaxCount=1,
+ InstanceType="t3.micro",
+)
+instance_id = reservation["Instances"][0]["InstanceId"]
+print(instance_id) # i-xxxxxxxxxxxxxxxxx
+
+# Security Groups
+sg = ec2.create_security_group(GroupName="my-sg", Description="My SG")
+ec2.authorize_security_group_ingress(
+ GroupId=sg["GroupId"],
+ IpPermissions=[{"IpProtocol": "tcp", "FromPort": 80, "ToPort": 80,
+ "IpRanges": [{"CidrIp": "0.0.0.0/0"}]}],
+)
+
+# VPC / Subnet
+vpc = ec2.create_vpc(CidrBlock="10.0.0.0/16")
+subnet = ec2.create_subnet(
+ VpcId=vpc["Vpc"]["VpcId"],
+ CidrBlock="10.0.1.0/24",
+ AvailabilityZone="us-east-1a",
+)
```
---
@@ -193,7 +220,7 @@ sfn.create_state_machine(
| **Kinesis** | CreateStream, DeleteStream, DescribeStream, ListStreams, ListShards, PutRecord, PutRecords, GetShardIterator, GetRecords, MergeShards, SplitShard, UpdateShardCount, StartStreamEncryption, StopStreamEncryption, EnableEnhancedMonitoring, DisableEnhancedMonitoring, RegisterStreamConsumer, DeregisterStreamConsumer, ListStreamConsumers, DescribeStreamConsumer, AddTagsToStream, RemoveTagsFromStream, ListTagsForStream | Partition key → shard routing |
| **CloudWatch Metrics** | PutMetricData, GetMetricStatistics, GetMetricData, ListMetrics, PutMetricAlarm, PutCompositeAlarm, DescribeAlarms, DescribeAlarmsForMetric, DescribeAlarmHistory, DeleteAlarms, SetAlarmState, EnableAlarmActions, DisableAlarmActions, TagResource, UntagResource, ListTagsForResource, PutDashboard, GetDashboard, DeleteDashboards, ListDashboards | CBOR and JSON protocol |
| **SES** | SendEmail, SendRawEmail, SendTemplatedEmail, SendBulkTemplatedEmail, VerifyEmailIdentity, VerifyEmailAddress, VerifyDomainIdentity, VerifyDomainDkim, ListIdentities, GetIdentityVerificationAttributes, GetIdentityDkimAttributes, DeleteIdentity, GetSendQuota, GetSendStatistics, CreateConfigurationSet, DeleteConfigurationSet, DescribeConfigurationSet, ListConfigurationSets, CreateTemplate, GetTemplate, UpdateTemplate, DeleteTemplate, ListTemplates | Emails stored in-memory, not sent |
-| **Step Functions** | CreateStateMachine, DeleteStateMachine, DescribeStateMachine, UpdateStateMachine, ListStateMachines, StartExecution, StartSyncExecution, StopExecution, DescribeExecution, DescribeStateMachineForExecution, ListExecutions, GetExecutionHistory, SendTaskSuccess, SendTaskFailure, SendTaskHeartbeat, TagResource, UntagResource, ListTagsForResource | Full ASL interpreter; Retry/Catch; waitForTaskToken; Pass/Task/Choice/Wait/Succeed/Fail/Map/Parallel |
+| **Step Functions** | CreateStateMachine, DeleteStateMachine, DescribeStateMachine, UpdateStateMachine, ListStateMachines, StartExecution, StartSyncExecution, StopExecution, DescribeExecution, DescribeStateMachineForExecution, ListExecutions, GetExecutionHistory, SendTaskSuccess, SendTaskFailure, SendTaskHeartbeat, CreateActivity, DeleteActivity, DescribeActivity, ListActivities, GetActivityTask, TagResource, UntagResource, ListTagsForResource | Full ASL interpreter; Retry/Catch; waitForTaskToken; Activities (worker pattern); Pass/Task/Choice/Wait/Succeed/Fail/Map/Parallel |
| **API Gateway v2** | CreateApi, GetApi, GetApis, UpdateApi, DeleteApi, CreateRoute, GetRoute, GetRoutes, UpdateRoute, DeleteRoute, CreateIntegration, GetIntegration, GetIntegrations, UpdateIntegration, DeleteIntegration, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateDeployment, GetDeployment, GetDeployments, DeleteDeployment, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, TagResource, UntagResource, GetTags | HTTP API (v2) protocol; Lambda proxy (AWS_PROXY) and HTTP proxy (HTTP_PROXY) integrations; data plane via `{apiId}.execute-api.localhost`; `{param}` and `{proxy+}` path matching; JWT/Lambda authorizer CRUD |
| **API Gateway v1** | CreateRestApi, GetRestApi, GetRestApis, UpdateRestApi, DeleteRestApi, CreateResource, GetResource, GetResources, UpdateResource, DeleteResource, PutMethod, GetMethod, DeleteMethod, UpdateMethod, PutMethodResponse, GetMethodResponse, DeleteMethodResponse, PutIntegration, GetIntegration, DeleteIntegration, UpdateIntegration, PutIntegrationResponse, GetIntegrationResponse, DeleteIntegrationResponse, CreateDeployment, GetDeployment, GetDeployments, UpdateDeployment, DeleteDeployment, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, CreateModel, GetModel, GetModels, DeleteModel, CreateApiKey, GetApiKey, GetApiKeys, UpdateApiKey, DeleteApiKey, CreateUsagePlan, GetUsagePlan, GetUsagePlans, UpdateUsagePlan, DeleteUsagePlan, CreateUsagePlanKey, GetUsagePlanKeys, DeleteUsagePlanKey, CreateDomainName, GetDomainName, GetDomainNames, DeleteDomainName, CreateBasePathMapping, GetBasePathMapping, GetBasePathMappings, DeleteBasePathMapping, TagResource, UntagResource, GetTags | REST API (v1) protocol; Lambda proxy format 1.0 (AWS_PROXY), HTTP proxy (HTTP_PROXY), MOCK integration; data plane via `{apiId}.execute-api.localhost`; resource tree with `{param}` and `{proxy+}` path matching; JSON Patch for all PATCH operations; state persistence |
@@ -208,6 +235,7 @@ sfn.create_state_machine(
| **Athena** | StartQueryExecution, GetQueryExecution, GetQueryResults, StopQueryExecution, ListQueryExecutions, BatchGetQueryExecution, CreateWorkGroup, DeleteWorkGroup, GetWorkGroup, ListWorkGroups, UpdateWorkGroup, CreateNamedQuery, DeleteNamedQuery, GetNamedQuery, ListNamedQueries, BatchGetNamedQuery, CreateDataCatalog, GetDataCatalog, ListDataCatalogs, DeleteDataCatalog, UpdateDataCatalog, CreatePreparedStatement, GetPreparedStatement, DeletePreparedStatement, ListPreparedStatements, GetTableMetadata, ListTableMetadata, TagResource, UntagResource, ListTagsForResource | Real SQL via **DuckDB** when installed (`pip install duckdb`), otherwise returns mock results; result pagination; column type metadata |
| **Firehose** | CreateDeliveryStream, DeleteDeliveryStream, DescribeDeliveryStream, ListDeliveryStreams, PutRecord, PutRecordBatch, UpdateDestination, TagDeliveryStream, UntagDeliveryStream, ListTagsForDeliveryStream, StartDeliveryStreamEncryption, StopDeliveryStreamEncryption | S3 destinations write records to the local S3 emulator; all other destination types buffer in-memory; concurrency-safe `UpdateDestination` via `VersionId` |
| **Route53** | CreateHostedZone, GetHostedZone, DeleteHostedZone, ListHostedZones, ListHostedZonesByName, UpdateHostedZoneComment, ChangeResourceRecordSets (CREATE/UPSERT/DELETE), ListResourceRecordSets, GetChange, CreateHealthCheck, GetHealthCheck, DeleteHealthCheck, ListHealthChecks, UpdateHealthCheck, ChangeTagsForResource, ListTagsForResource | REST/XML protocol; SOA + NS records auto-created; CallerReference idempotency; alias records, weighted/failover/latency routing; marker-based pagination |
+| **EC2** | RunInstances, DescribeInstances, TerminateInstances, StopInstances, StartInstances, RebootInstances, DescribeImages, CreateSecurityGroup, DeleteSecurityGroup, DescribeSecurityGroups, AuthorizeSecurityGroupIngress, RevokeSecurityGroupIngress, AuthorizeSecurityGroupEgress, RevokeSecurityGroupEgress, CreateKeyPair, DeleteKeyPair, DescribeKeyPairs, ImportKeyPair, CreateVpc, DeleteVpc, DescribeVpcs, ModifyVpcAttribute, CreateSubnet, DeleteSubnet, DescribeSubnets, ModifySubnetAttribute, CreateInternetGateway, DeleteInternetGateway, DescribeInternetGateways, AttachInternetGateway, DetachInternetGateway, CreateRouteTable, DeleteRouteTable, DescribeRouteTables, AssociateRouteTable, DisassociateRouteTable, CreateRoute, ReplaceRoute, DeleteRoute, CreateNetworkInterface, DeleteNetworkInterface, DescribeNetworkInterfaces, AttachNetworkInterface, DetachNetworkInterface, CreateVpcEndpoint, DeleteVpcEndpoints, DescribeVpcEndpoints, DescribeAvailabilityZones, AllocateAddress, ReleaseAddress, AssociateAddress, DisassociateAddress, DescribeAddresses, CreateTags, DeleteTags, DescribeTags | In-memory state only — no real VMs; default VPC, subnet, security group, internet gateway, and route table always present; rules stored but not enforced (matches LocalStack) |
| **Cognito** | **User Pools**: CreateUserPool, DeleteUserPool, DescribeUserPool, ListUserPools, UpdateUserPool, CreateUserPoolClient, DeleteUserPoolClient, DescribeUserPoolClient, ListUserPoolClients, UpdateUserPoolClient, AdminCreateUser, AdminDeleteUser, AdminGetUser, ListUsers, AdminSetUserPassword, AdminUpdateUserAttributes, AdminConfirmSignUp, AdminDisableUser, AdminEnableUser, AdminResetUserPassword, AdminUserGlobalSignOut, AdminAddUserToGroup, AdminRemoveUserFromGroup, AdminListGroupsForUser, AdminListUserAuthEvents, AdminInitiateAuth, AdminRespondToAuthChallenge, InitiateAuth, RespondToAuthChallenge, GlobalSignOut, RevokeToken, SignUp, ConfirmSignUp, ForgotPassword, ConfirmForgotPassword, ChangePassword, GetUser, UpdateUserAttributes, DeleteUser, CreateGroup, DeleteGroup, GetGroup, ListGroups, ListUsersInGroup, CreateUserPoolDomain, DeleteUserPoolDomain, DescribeUserPoolDomain, GetUserPoolMfaConfig, SetUserPoolMfaConfig, AssociateSoftwareToken, VerifySoftwareToken, TagResource, UntagResource, ListTagsForResource; **Identity Pools**: CreateIdentityPool, DeleteIdentityPool, DescribeIdentityPool, ListIdentityPools, UpdateIdentityPool, GetId, GetCredentialsForIdentity, GetOpenIdToken, SetIdentityPoolRoles, GetIdentityPoolRoles, ListIdentities, DescribeIdentity, MergeDeveloperIdentities, UnlinkDeveloperIdentity, UnlinkIdentity, TagResource, UntagResource, ListTagsForResource; **OAuth2**: /oauth2/token (client_credentials) | Stub JWT tokens (structurally valid base64url JWTs); SRP auth returns PASSWORD_VERIFIER challenge; confirmation codes hardcoded (signup: 123456, forgot-password: 654321); MFA config stored in-memory |
---
@@ -398,7 +426,7 @@ MiniStack keeps Python Lambda functions warm between invocations. After the firs
│ │ Step Functions API GW v1/v2 │ │
│ │ ECS RDS ElastiCache Glue │ │
│ │ Athena Firehose Route53 │ │
- │ │ Cognito │ │
+ │ │ Cognito EC2 │ │
│ └──────────────────────────────────┘ │
│ │
│ In-Memory Storage + Optional Docker │
@@ -421,19 +449,19 @@ pip install boto3 pytest duckdb docker cbor2
# Start MiniStack
docker compose up -d
-# Run the full test suite (613 tests across all 25 services)
+# Run the full test suite (644 tests across all 26 services)
pytest tests/ -v
```
Expected output:
```
-collected 613 items
+collected 644 items
tests/test_services.py::test_s3_create_bucket PASSED
...
tests/test_services.py::test_app_asgi_callable PASSED
-613 passed in ~60s
+644 passed in ~60s
```
---
@@ -477,6 +505,7 @@ provider "aws" {
route53 = "http://localhost:4566"
cognitoidp = "http://localhost:4566"
cognitoidentity = "http://localhost:4566"
+ ec2 = "http://localhost:4566"
}
}
```
@@ -526,6 +555,7 @@ config:
| **Firehose** | ✅ | ✅ | ✅ |
| **Route53** | ✅ | ✅ | ✅ |
| **Cognito** | ✅ | ✅ | ✅ |
+| **EC2** | ✅ | ✅ | ✅ |
| CloudFormation | ❌ | partial | ✅ |
| Cost | **Free** | Was free, now paid | $35+/mo |
| Docker image size | ~150MB | ~1GB | ~1GB |
diff --git a/ministack/app.py b/ministack/app.py
index b4532a72..81b6cf37 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -25,6 +25,7 @@ from ministack.core.persistence import save_all, load_state, PERSIST_STATE
from ministack.services import s3, sqs, sns, dynamodb, lambda_svc, secretsmanager, cloudwatch_logs
from ministack.services import ssm, eventbridge, kinesis, cloudwatch, ses, stepfunctions
from ministack.services import ecs, rds, elasticache, glue, athena
+from ministack.services import ec2
from ministack.services import apigateway
from ministack.services import firehose
from ministack.services import apigateway_v1
@@ -66,6 +67,7 @@ SERVICE_HANDLERS = {
"route53": route53.handle_request,
"cognito-idp": cognito.handle_request,
"cognito-identity": cognito.handle_request,
+ "ec2": ec2.handle_request,
}
SERVICE_NAME_ALIASES = {
@@ -372,6 +374,7 @@ def _reset_all_state():
(firehose, firehose.reset),
(route53, route53.reset),
(cognito, cognito.reset),
+ (ec2, ec2.reset),
]:
try:
fn()
diff --git a/ministack/core/router.py b/ministack/core/router.py
index dd1679f1..303cf058 100644
--- a/ministack/core/router.py
+++ b/ministack/core/router.py
@@ -116,6 +116,13 @@ SERVICE_PATTERNS = {
"target_prefixes": ["AWSCognitoIdentityService"],
"host_patterns": [r"cognito-identity\."],
},
+ "ec2": {
+ "host_patterns": [r"ec2\."],
+ "path_patterns": [r"Action=.*Instance", r"Action=.*Security", r"Action=.*KeyPair",
+ r"Action=.*Vpc", r"Action=.*Subnet", r"Action=.*Address",
+ r"Action=.*Image", r"Action=.*Tag", r"Action=.*InternetGateway",
+ r"Action=.*AvailabilityZone"],
+ },
}
@@ -264,6 +271,35 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->
"CreateSnapshot": "elasticache", "DeleteSnapshot": "elasticache",
"DescribeSnapshots": "elasticache",
"IncreaseReplicaCount": "elasticache", "DecreaseReplicaCount": "elasticache",
+ # EC2 actions
+ "RunInstances": "ec2", "DescribeInstances": "ec2", "TerminateInstances": "ec2",
+ "StopInstances": "ec2", "StartInstances": "ec2", "RebootInstances": "ec2",
+ "DescribeImages": "ec2",
+ "CreateSecurityGroup": "ec2", "DeleteSecurityGroup": "ec2",
+ "DescribeSecurityGroups": "ec2",
+ "AuthorizeSecurityGroupIngress": "ec2", "RevokeSecurityGroupIngress": "ec2",
+ "AuthorizeSecurityGroupEgress": "ec2", "RevokeSecurityGroupEgress": "ec2",
+ "CreateKeyPair": "ec2", "DeleteKeyPair": "ec2", "DescribeKeyPairs": "ec2",
+ "ImportKeyPair": "ec2",
+ "DescribeVpcs": "ec2", "CreateVpc": "ec2", "DeleteVpc": "ec2",
+ "DescribeSubnets": "ec2", "CreateSubnet": "ec2", "DeleteSubnet": "ec2",
+ "CreateInternetGateway": "ec2", "DeleteInternetGateway": "ec2",
+ "DescribeInternetGateways": "ec2",
+ "AttachInternetGateway": "ec2", "DetachInternetGateway": "ec2",
+ "DescribeAvailabilityZones": "ec2",
+ "AllocateAddress": "ec2", "ReleaseAddress": "ec2",
+ "AssociateAddress": "ec2", "DisassociateAddress": "ec2",
+ "DescribeAddresses": "ec2",
+ "CreateTags": "ec2", "DeleteTags": "ec2", "DescribeTags": "ec2",
+ "ModifyVpcAttribute": "ec2", "ModifySubnetAttribute": "ec2",
+ "CreateRouteTable": "ec2", "DeleteRouteTable": "ec2", "DescribeRouteTables": "ec2",
+ "AssociateRouteTable": "ec2", "DisassociateRouteTable": "ec2",
+ "CreateRoute": "ec2", "ReplaceRoute": "ec2", "DeleteRoute": "ec2",
+ "CreateNetworkInterface": "ec2", "DeleteNetworkInterface": "ec2",
+ "DescribeNetworkInterfaces": "ec2",
+ "AttachNetworkInterface": "ec2", "DetachNetworkInterface": "ec2",
+ "CreateVpcEndpoint": "ec2", "DeleteVpcEndpoints": "ec2",
+ "DescribeVpcEndpoints": "ec2",
}
if action in action_service_map:
return action_service_map[action]
diff --git a/ministack/services/ec2.py b/ministack/services/ec2.py
new file mode 100644
index 00000000..2adb219d
--- /dev/null
+++ b/ministack/services/ec2.py
@@ -0,0 +1,1477 @@
+"""
+EC2 Service Emulator.
+Query API (Action=...) — instances exist in memory only, no real VMs launched.
+
+Supports:
+ Instances: RunInstances, TerminateInstances, DescribeInstances,
+ StartInstances, StopInstances, RebootInstances
+ Images: DescribeImages (stub — returns common AMI IDs)
+ Security Groups: CreateSecurityGroup, DeleteSecurityGroup, DescribeSecurityGroups,
+ AuthorizeSecurityGroupIngress, RevokeSecurityGroupIngress,
+ AuthorizeSecurityGroupEgress, RevokeSecurityGroupEgress
+ Key Pairs: CreateKeyPair, DeleteKeyPair, DescribeKeyPairs, ImportKeyPair
+ VPC / Subnets: DescribeVpcs, DescribeSubnets, DescribeAvailabilityZones
+ CreateVpc, DeleteVpc, CreateSubnet, DeleteSubnet
+ CreateInternetGateway, DeleteInternetGateway, DescribeInternetGateways,
+ AttachInternetGateway, DetachInternetGateway
+ Elastic IPs: AllocateAddress, ReleaseAddress, AssociateAddress, DisassociateAddress,
+ DescribeAddresses
+ Tags: CreateTags, DeleteTags, DescribeTags
+ VPC attributes: ModifyVpcAttribute, ModifySubnetAttribute
+ Route Tables: CreateRouteTable, DeleteRouteTable, DescribeRouteTables,
+ AssociateRouteTable, DisassociateRouteTable,
+ CreateRoute, ReplaceRoute, DeleteRoute
+ ENI: CreateNetworkInterface, DeleteNetworkInterface, DescribeNetworkInterfaces,
+ AttachNetworkInterface, DetachNetworkInterface
+ VPC Endpoints: CreateVpcEndpoint, DeleteVpcEndpoints, DescribeVpcEndpoints
+"""
+
+import os
+import time
+import random
+import string
+import logging
+from urllib.parse import parse_qs
+
+from ministack.core.responses import new_uuid
+
+logger = logging.getLogger("ec2")
+
+ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
+REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
+
+# ---------------------------------------------------------------------------
+# State
+# ---------------------------------------------------------------------------
+
+_instances: dict = {}
+_security_groups: dict = {}
+_key_pairs: dict = {}
+_vpcs: dict = {}
+_subnets: dict = {}
+_internet_gateways: dict = {}
+_addresses: dict = {} # allocation_id -> address record
+_tags: dict = {} # resource_id -> [{"Key": ..., "Value": ...}]
+_route_tables: dict = {} # rtb_id -> route table record
+_network_interfaces: dict = {} # eni_id -> ENI record
+_vpc_endpoints: dict = {} # vpce_id -> endpoint record
+
+# Default VPC / subnet created at import time so DescribeVpcs always returns something
+_DEFAULT_VPC_ID = "vpc-00000001"
+_DEFAULT_SUBNET_ID = "subnet-00000001"
+_DEFAULT_SG_ID = "sg-00000001"
+_DEFAULT_IGW_ID = "igw-00000001"
+
+
+def _init_defaults():
+ if _DEFAULT_VPC_ID not in _vpcs:
+ _vpcs[_DEFAULT_VPC_ID] = {
+ "VpcId": _DEFAULT_VPC_ID,
+ "CidrBlock": "172.31.0.0/16",
+ "State": "available",
+ "IsDefault": True,
+ "DhcpOptionsId": "dopt-00000001",
+ "InstanceTenancy": "default",
+ "OwnerId": ACCOUNT_ID,
+ }
+ if _DEFAULT_SUBNET_ID not in _subnets:
+ _subnets[_DEFAULT_SUBNET_ID] = {
+ "SubnetId": _DEFAULT_SUBNET_ID,
+ "VpcId": _DEFAULT_VPC_ID,
+ "CidrBlock": "172.31.0.0/20",
+ "AvailabilityZone": f"{REGION}a",
+ "AvailableIpAddressCount": 4091,
+ "State": "available",
+ "DefaultForAz": True,
+ "MapPublicIpOnLaunch": True,
+ "OwnerId": ACCOUNT_ID,
+ }
+ if _DEFAULT_SG_ID not in _security_groups:
+ _security_groups[_DEFAULT_SG_ID] = {
+ "GroupId": _DEFAULT_SG_ID,
+ "GroupName": "default",
+ "Description": "default VPC security group",
+ "VpcId": _DEFAULT_VPC_ID,
+ "OwnerId": ACCOUNT_ID,
+ "IpPermissions": [],
+ "IpPermissionsEgress": [
+ {"IpProtocol": "-1", "IpRanges": [{"CidrIp": "0.0.0.0/0"}],
+ "Ipv6Ranges": [], "PrefixListIds": [], "UserIdGroupPairs": []},
+ ],
+ }
+ if _DEFAULT_IGW_ID not in _internet_gateways:
+ _internet_gateways[_DEFAULT_IGW_ID] = {
+ "InternetGatewayId": _DEFAULT_IGW_ID,
+ "OwnerId": ACCOUNT_ID,
+ "Attachments": [{"VpcId": _DEFAULT_VPC_ID, "State": "available"}],
+ }
+ default_rtb = "rtb-00000001"
+ if default_rtb not in _route_tables:
+ _route_tables[default_rtb] = {
+ "RouteTableId": default_rtb,
+ "VpcId": _DEFAULT_VPC_ID,
+ "OwnerId": ACCOUNT_ID,
+ "Routes": [
+ {"DestinationCidrBlock": "172.31.0.0/16", "GatewayId": "local",
+ "State": "active", "Origin": "CreateRouteTable"},
+ ],
+ "Associations": [
+ {"RouteTableAssociationId": "rtbassoc-00000001",
+ "RouteTableId": default_rtb,
+ "Main": True, "AssociationState": {"State": "associated"}},
+ ],
+ }
+
+
+_init_defaults()
+
+
+# ---------------------------------------------------------------------------
+# Request routing
+# ---------------------------------------------------------------------------
+
+async def handle_request(method, path, headers, body, query_params):
+ params = dict(query_params)
+ if method in ("POST", "PUT") and body:
+ raw = body if isinstance(body, str) else body.decode("utf-8", errors="replace")
+ for k, v in parse_qs(raw).items():
+ params[k] = v
+
+ action = _p(params, "Action")
+ handler = _ACTION_MAP.get(action)
+ if not handler:
+ return _error("InvalidAction", f"Unknown EC2 action: {action}", 400)
+ return handler(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")
+ 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]
+
+ now = _now_ts()
+ created = []
+ for _ in range(max(1, min(min_count, max_count))):
+ instance_id = _new_instance_id()
+ private_ip = _random_ip("10.0")
+ _instances[instance_id] = {
+ "InstanceId": instance_id,
+ "ImageId": image_id,
+ "InstanceType": instance_type,
+ "KeyName": key_name,
+ "State": {"Code": 16, "Name": "running"},
+ "SubnetId": subnet_id,
+ "VpcId": _vpcs.get(
+ _subnets.get(subnet_id, {}).get("VpcId", _DEFAULT_VPC_ID),
+ {},
+ ).get("VpcId", _DEFAULT_VPC_ID),
+ "PrivateIpAddress": private_ip,
+ "PublicIpAddress": _random_ip("54."),
+ "PrivateDnsName": f"ip-{private_ip.replace('.', '-')}.ec2.internal",
+ "PublicDnsName": f"ec2-{private_ip.replace('.', '-')}.compute-1.amazonaws.com",
+ "SecurityGroups": [
+ {"GroupId": sg, "GroupName": _security_groups.get(sg, {}).get("GroupName", sg)}
+ for sg in sg_ids
+ ],
+ "Architecture": "x86_64",
+ "RootDeviceType": "ebs",
+ "RootDeviceName": "/dev/xvda",
+ "Hypervisor": "xen",
+ "Virtualization": "hvm",
+ "Placement": {"AvailabilityZone": f"{REGION}a", "Tenancy": "default"},
+ "Monitoring": {"State": "disabled"},
+ "AmiLaunchIndex": 0,
+ "UserData": user_data,
+ "LaunchTime": now,
+ }
+ created.append(_instances[instance_id])
+
+ items = "".join(_instance_xml(i) for i in created)
+ inner = f"""<instancesSet>{items}</instancesSet>
+ <reservationId>r-{new_uuid().replace('-','')[:17]}</reservationId>
+ <ownerId>{ACCOUNT_ID}</ownerId>
+ <groupSet/>"""
+ return _xml(200, "RunInstancesResponse", inner)
+
+
+def _describe_instances(p):
+ filter_ids = _parse_member_list(p, "InstanceId")
+ filters = _parse_filters(p)
+
+ results = []
+ for inst in _instances.values():
+ if filter_ids and inst["InstanceId"] not in filter_ids:
+ continue
+ if not _matches_filters(inst, filters):
+ continue
+ results.append(inst)
+
+ items = "".join(
+ f"""<item>
+ <reservationId>r-{inst['InstanceId'][2:]}</reservationId>
+ <ownerId>{ACCOUNT_ID}</ownerId>
+ <groupSet/>
+ <instancesSet>{_instance_xml(inst)}</instancesSet>
+ </item>"""
+ for inst in results
+ )
+ return _xml(200, "DescribeInstancesResponse", f"<reservationSet>{items}</reservationSet>")
+
+
+def _terminate_instances(p):
+ ids = _parse_member_list(p, "InstanceId")
+ items = ""
+ for iid in ids:
+ inst = _instances.get(iid)
+ if inst:
+ prev = inst["State"].copy()
+ inst["State"] = {"Code": 48, "Name": "terminated"}
+ items += f"""<item>
+ <instanceId>{iid}</instanceId>
+ <previousState><code>{prev['Code']}</code><name>{prev['Name']}</name></previousState>
+ <currentState><code>48</code><name>terminated</name></currentState>
+ </item>"""
+ return _xml(200, "TerminateInstancesResponse", f"<instancesSet>{items}</instancesSet>")
+
+
+def _stop_instances(p):
+ ids = _parse_member_list(p, "InstanceId")
+ items = ""
+ for iid in ids:
+ inst = _instances.get(iid)
+ if inst:
+ prev = inst["State"].copy()
+ inst["State"] = {"Code": 80, "Name": "stopped"}
+ items += f"""<item>
+ <instanceId>{iid}</instanceId>
+ <previousState><code>{prev['Code']}</code><name>{prev['Name']}</name></previousState>
+ <currentState><code>80</code><name>stopped</name></currentState>
+ </item>"""
+ return _xml(200, "StopInstancesResponse", f"<instancesSet>{items}</instancesSet>")
+
+
+def _start_instances(p):
+ ids = _parse_member_list(p, "InstanceId")
+ items = ""
+ for iid in ids:
+ inst = _instances.get(iid)
+ if inst:
+ prev = inst["State"].copy()
+ inst["State"] = {"Code": 16, "Name": "running"}
+ items += f"""<item>
+ <instanceId>{iid}</instanceId>
+ <previousState><code>{prev['Code']}</code><name>{prev['Name']}</name></previousState>
+ <currentState><code>16</code><name>running</name></currentState>
+ </item>"""
+ return _xml(200, "StartInstancesResponse", f"<instancesSet>{items}</instancesSet>")
+
+
+def _reboot_instances(p):
+ return _xml(200, "RebootInstancesResponse", "<return>true</return>")
+
+
+# ---------------------------------------------------------------------------
+# Images (AMIs) — stub
+# ---------------------------------------------------------------------------
+
+_STUB_AMIS = [
+ ("ami-0abcdef1234567890", "amzn2-ami-hvm-2.0.20231116.0-x86_64-gp2", "Amazon Linux 2"),
+ ("ami-0123456789abcdef0", "ubuntu/images/hvm-ssd/ubuntu-22.04-amd64-server", "Ubuntu 22.04"),
+ ("ami-0fedcba9876543210", "Windows_Server-2022-English-Full-Base", "Windows Server 2022"),
+]
+
+
+def _describe_images(p):
+ filter_ids = _parse_member_list(p, "ImageId")
+ items = ""
+ for ami_id, name, desc in _STUB_AMIS:
+ if filter_ids and ami_id not in filter_ids:
+ continue
+ items += f"""<item>
+ <imageId>{ami_id}</imageId>
+ <imageLocation>{name}</imageLocation>
+ <imageState>available</imageState>
+ <imageOwnerId>{ACCOUNT_ID}</imageOwnerId>
+ <isPublic>true</isPublic>
+ <architecture>x86_64</architecture>
+ <imageType>machine</imageType>
+ <name>{name}</name>
+ <description>{desc}</description>
+ <rootDeviceType>ebs</rootDeviceType>
+ <virtualizationType>hvm</virtualizationType>
+ <hypervisor>xen</hypervisor>
+ </item>"""
+ return _xml(200, "DescribeImagesResponse", f"<imagesSet>{items}</imagesSet>")
+
+
+# ---------------------------------------------------------------------------
+# Security Groups
+# ---------------------------------------------------------------------------
+
+def _create_security_group(p):
+ name = _p(p, "GroupName")
+ desc = _p(p, "Description") or name
+ vpc_id = _p(p, "VpcId") or _DEFAULT_VPC_ID
+ if not name:
+ return _error("MissingParameter", "GroupName is required", 400)
+
+ for sg in _security_groups.values():
+ if sg["GroupName"] == name and sg["VpcId"] == vpc_id:
+ return _error("InvalidGroup.Duplicate",
+ f"The security group '{name}' already exists", 400)
+
+ sg_id = _new_sg_id()
+ _security_groups[sg_id] = {
+ "GroupId": sg_id,
+ "GroupName": name,
+ "Description": desc,
+ "VpcId": vpc_id,
+ "OwnerId": ACCOUNT_ID,
+ "IpPermissions": [],
+ "IpPermissionsEgress": [],
+ }
+ return _xml(200, "CreateSecurityGroupResponse",
+ f"<return>true</return><groupId>{sg_id}</groupId>")
+
+
+def _delete_security_group(p):
+ sg_id = _p(p, "GroupId")
+ if sg_id and sg_id in _security_groups:
+ del _security_groups[sg_id]
+ elif sg_id:
+ return _error("InvalidGroup.NotFound",
+ f"The security group '{sg_id}' does not exist", 400)
+ return _xml(200, "DeleteSecurityGroupResponse", "<return>true</return>")
+
+
+def _describe_security_groups(p):
+ filter_ids = _parse_member_list(p, "GroupId")
+ items = ""
+ for sg in _security_groups.values():
+ if filter_ids and sg["GroupId"] not in filter_ids:
+ continue
+ items += _sg_xml(sg)
+ return _xml(200, "DescribeSecurityGroupsResponse",
+ f"<securityGroupInfo>{items}</securityGroupInfo>")
+
+
+def _authorize_sg_ingress(p):
+ sg_id = _p(p, "GroupId")
+ sg = _security_groups.get(sg_id)
+ if not sg:
+ return _error("InvalidGroup.NotFound", f"Security group {sg_id} not found", 400)
+ rules = _parse_ip_permissions(p, "IpPermissions")
+ sg["IpPermissions"].extend(rules)
+ return _xml(200, "AuthorizeSecurityGroupIngressResponse", "<return>true</return>")
+
+
+def _revoke_sg_ingress(p):
+ sg_id = _p(p, "GroupId")
+ sg = _security_groups.get(sg_id)
+ if not sg:
+ return _error("InvalidGroup.NotFound", f"Security group {sg_id} not found", 400)
+ rules = _parse_ip_permissions(p, "IpPermissions")
+ for r in rules:
+ try:
+ sg["IpPermissions"].remove(r)
+ except ValueError:
+ pass
+ return _xml(200, "RevokeSecurityGroupIngressResponse", "<return>true</return>")
+
+
+def _authorize_sg_egress(p):
+ sg_id = _p(p, "GroupId")
+ sg = _security_groups.get(sg_id)
+ if not sg:
+ return _error("InvalidGroup.NotFound", f"Security group {sg_id} not found", 400)
+ rules = _parse_ip_permissions(p, "IpPermissions")
+ sg["IpPermissionsEgress"].extend(rules)
+ return _xml(200, "AuthorizeSecurityGroupEgressResponse", "<return>true</return>")
+
+
+def _revoke_sg_egress(p):
+ sg_id = _p(p, "GroupId")
+ sg = _security_groups.get(sg_id)
+ if not sg:
+ return _error("InvalidGroup.NotFound", f"Security group {sg_id} not found", 400)
+ rules = _parse_ip_permissions(p, "IpPermissions")
+ for r in rules:
+ try:
+ sg["IpPermissionsEgress"].remove(r)
+ except ValueError:
+ pass
+ return _xml(200, "RevokeSecurityGroupEgressResponse", "<return>true</return>")
+
+
+# ---------------------------------------------------------------------------
+# Key Pairs
+# ---------------------------------------------------------------------------
+
+def _create_key_pair(p):
+ name = _p(p, "KeyName")
+ if not name:
+ return _error("MissingParameter", "KeyName is required", 400)
+ if name in _key_pairs:
+ return _error("InvalidKeyPair.Duplicate",
+ f"The key pair '{name}' already exists", 400)
+ fingerprint = ":".join(f"{random.randint(0,255):02x}" for _ in range(20))
+ material = "-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA(stub)\n-----END RSA PRIVATE KEY-----"
+ _key_pairs[name] = {
+ "KeyName": name,
+ "KeyFingerprint": fingerprint,
+ "KeyPairId": f"key-{new_uuid().replace('-','')[:17]}",
+ }
+ return _xml(200, "CreateKeyPairResponse", f"""
+ <keyName>{name}</keyName>
+ <keyFingerprint>{fingerprint}</keyFingerprint>
+ <keyMaterial>{material}</keyMaterial>
+ <keyPairId>{_key_pairs[name]['KeyPairId']}</keyPairId>""")
+
+
+def _delete_key_pair(p):
+ name = _p(p, "KeyName")
+ _key_pairs.pop(name, None)
+ return _xml(200, "DeleteKeyPairResponse", "<return>true</return>")
+
+
+def _describe_key_pairs(p):
+ filter_names = _parse_member_list(p, "KeyName")
+ items = ""
+ for kp in _key_pairs.values():
+ if filter_names and kp["KeyName"] not in filter_names:
+ continue
+ items += f"""<item>
+ <keyName>{kp['KeyName']}</keyName>
+ <keyFingerprint>{kp['KeyFingerprint']}</keyFingerprint>
+ <keyPairId>{kp['KeyPairId']}</keyPairId>
+ </item>"""
+ return _xml(200, "DescribeKeyPairsResponse", f"<keySet>{items}</keySet>")
+
+
+def _import_key_pair(p):
+ name = _p(p, "KeyName")
+ if not name:
+ return _error("MissingParameter", "KeyName is required", 400)
+ fingerprint = ":".join(f"{random.randint(0,255):02x}" for _ in range(20))
+ _key_pairs[name] = {
+ "KeyName": name,
+ "KeyFingerprint": fingerprint,
+ "KeyPairId": f"key-{new_uuid().replace('-','')[:17]}",
+ }
+ return _xml(200, "ImportKeyPairResponse", f"""
+ <keyName>{name}</keyName>
+ <keyFingerprint>{fingerprint}</keyFingerprint>
+ <keyPairId>{_key_pairs[name]['KeyPairId']}</keyPairId>""")
+
+
+# ---------------------------------------------------------------------------
+# VPCs
+# ---------------------------------------------------------------------------
+
+def _describe_vpcs(p):
+ filter_ids = _parse_member_list(p, "VpcId")
+ items = ""
+ for vpc in _vpcs.values():
+ if filter_ids and vpc["VpcId"] not in filter_ids:
+ continue
+ items += _vpc_xml(vpc)
+ return _xml(200, "DescribeVpcsResponse", f"<vpcSet>{items}</vpcSet>")
+
+
+def _create_vpc(p):
+ cidr = _p(p, "CidrBlock") or "10.0.0.0/16"
+ vpc_id = _new_vpc_id()
+ _vpcs[vpc_id] = {
+ "VpcId": vpc_id,
+ "CidrBlock": cidr,
+ "State": "available",
+ "IsDefault": False,
+ "DhcpOptionsId": "dopt-00000001",
+ "InstanceTenancy": _p(p, "InstanceTenancy") or "default",
+ "OwnerId": ACCOUNT_ID,
+ }
+ return _xml(200, "CreateVpcResponse", _vpc_fields_xml(_vpcs[vpc_id], tag="vpc"))
+
+
+def _delete_vpc(p):
+ vpc_id = _p(p, "VpcId")
+ if vpc_id not in _vpcs:
+ return _error("InvalidVpcID.NotFound", f"The vpc ID '{vpc_id}' does not exist", 400)
+ del _vpcs[vpc_id]
+ return _xml(200, "DeleteVpcResponse", "<return>true</return>")
+
+
+# ---------------------------------------------------------------------------
+# Subnets
+# ---------------------------------------------------------------------------
+
+def _describe_subnets(p):
+ filter_ids = _parse_member_list(p, "SubnetId")
+ items = ""
+ for subnet in _subnets.values():
+ if filter_ids and subnet["SubnetId"] not in filter_ids:
+ continue
+ items += _subnet_xml(subnet)
+ return _xml(200, "DescribeSubnetsResponse", f"<subnetSet>{items}</subnetSet>")
+
+
+def _create_subnet(p):
+ vpc_id = _p(p, "VpcId") or _DEFAULT_VPC_ID
+ cidr = _p(p, "CidrBlock") or "10.0.1.0/24"
+ az = _p(p, "AvailabilityZone") or f"{REGION}a"
+ subnet_id = _new_subnet_id()
+ _subnets[subnet_id] = {
+ "SubnetId": subnet_id,
+ "VpcId": vpc_id,
+ "CidrBlock": cidr,
+ "AvailabilityZone": az,
+ "AvailableIpAddressCount": 251,
+ "State": "available",
+ "DefaultForAz": False,
+ "MapPublicIpOnLaunch": False,
+ "OwnerId": ACCOUNT_ID,
+ }
+ return _xml(200, "CreateSubnetResponse", _subnet_fields_xml(_subnets[subnet_id], tag="subnet"))
+
+
+def _delete_subnet(p):
+ subnet_id = _p(p, "SubnetId")
+ if subnet_id not in _subnets:
+ return _error("InvalidSubnetID.NotFound",
+ f"The subnet ID '{subnet_id}' does not exist", 400)
+ del _subnets[subnet_id]
+ return _xml(200, "DeleteSubnetResponse", "<return>true</return>")
+
+
+# ---------------------------------------------------------------------------
+# Internet Gateways
+# ---------------------------------------------------------------------------
+
+def _create_internet_gateway(p):
+ igw_id = _new_igw_id()
+ _internet_gateways[igw_id] = {
+ "InternetGatewayId": igw_id,
+ "OwnerId": ACCOUNT_ID,
+ "Attachments": [],
+ }
+ return _xml(200, "CreateInternetGatewayResponse",
+ _igw_fields_xml(_internet_gateways[igw_id], tag="internetGateway"))
+
+
+def _delete_internet_gateway(p):
+ igw_id = _p(p, "InternetGatewayId")
+ if igw_id not in _internet_gateways:
+ return _error("InvalidInternetGatewayID.NotFound",
+ f"The internet gateway ID '{igw_id}' does not exist", 400)
+ del _internet_gateways[igw_id]
+ return _xml(200, "DeleteInternetGatewayResponse", "<return>true</return>")
+
+
+def _describe_internet_gateways(p):
+ filter_ids = _parse_member_list(p, "InternetGatewayId")
+ items = ""
+ for igw in _internet_gateways.values():
+ if filter_ids and igw["InternetGatewayId"] not in filter_ids:
+ continue
+ items += _igw_xml(igw)
+ return _xml(200, "DescribeInternetGatewaysResponse",
+ f"<internetGatewaySet>{items}</internetGatewaySet>")
+
+
+def _attach_internet_gateway(p):
+ igw_id = _p(p, "InternetGatewayId")
+ vpc_id = _p(p, "VpcId")
+ igw = _internet_gateways.get(igw_id)
+ if not igw:
+ return _error("InvalidInternetGatewayID.NotFound",
+ f"The internet gateway ID '{igw_id}' does not exist", 400)
+ igw["Attachments"] = [{"VpcId": vpc_id, "State": "available"}]
+ return _xml(200, "AttachInternetGatewayResponse", "<return>true</return>")
+
+
+def _detach_internet_gateway(p):
+ igw_id = _p(p, "InternetGatewayId")
+ igw = _internet_gateways.get(igw_id)
+ if igw:
+ igw["Attachments"] = []
+ return _xml(200, "DetachInternetGatewayResponse", "<return>true</return>")
+
+
+# ---------------------------------------------------------------------------
+# VPC / Subnet attribute modifications
+# ---------------------------------------------------------------------------
+
+def _modify_vpc_attribute(p):
+ vpc_id = _p(p, "VpcId")
+ if vpc_id not in _vpcs:
+ return _error("InvalidVpcID.NotFound", f"The vpc ID '{vpc_id}' does not exist", 400)
+ # EnableDnsSupport / EnableDnsHostnames — store but don't enforce
+ for attr in ("EnableDnsSupport.Value", "EnableDnsHostnames.Value"):
+ val = _p(p, attr)
+ if val:
+ _vpcs[vpc_id][attr.split(".")[0]] = val.lower() == "true"
+ return _xml(200, "ModifyVpcAttributeResponse", "<return>true</return>")
+
+
+def _modify_subnet_attribute(p):
+ subnet_id = _p(p, "SubnetId")
+ if subnet_id not in _subnets:
+ return _error("InvalidSubnetID.NotFound",
+ f"The subnet ID '{subnet_id}' does not exist", 400)
+ val = _p(p, "MapPublicIpOnLaunch.Value")
+ if val:
+ _subnets[subnet_id]["MapPublicIpOnLaunch"] = val.lower() == "true"
+ return _xml(200, "ModifySubnetAttributeResponse", "<return>true</return>")
+
+
+# ---------------------------------------------------------------------------
+# Route Tables
+# ---------------------------------------------------------------------------
+
+def _create_route_table(p):
+ vpc_id = _p(p, "VpcId") or _DEFAULT_VPC_ID
+ rtb_id = "rtb-" + "".join(random.choices(string.hexdigits[:16], k=17))
+ _route_tables[rtb_id] = {
+ "RouteTableId": rtb_id,
+ "VpcId": vpc_id,
+ "OwnerId": ACCOUNT_ID,
+ "Routes": [
+ {"DestinationCidrBlock": _vpcs.get(vpc_id, {}).get("CidrBlock", "10.0.0.0/16"),
+ "GatewayId": "local", "State": "active", "Origin": "CreateRouteTable"},
+ ],
+ "Associations": [],
+ }
+ return _xml(200, "CreateRouteTableResponse",
+ _rtb_fields_xml(_route_tables[rtb_id], tag="routeTable"))
+
+
+def _delete_route_table(p):
+ rtb_id = _p(p, "RouteTableId")
+ if rtb_id not in _route_tables:
+ return _error("InvalidRouteTableID.NotFound",
+ f"The route table '{rtb_id}' does not exist", 400)
+ del _route_tables[rtb_id]
+ return _xml(200, "DeleteRouteTableResponse", "<return>true</return>")
+
+
+def _describe_route_tables(p):
+ filter_ids = _parse_member_list(p, "RouteTableId")
+ items = "".join(
+ _rtb_fields_xml(rtb)
+ for rtb in _route_tables.values()
+ if not filter_ids or rtb["RouteTableId"] in filter_ids
+ )
+ return _xml(200, "DescribeRouteTablesResponse",
+ f"<routeTableSet>{items}</routeTableSet>")
+
+
+def _associate_route_table(p):
+ rtb_id = _p(p, "RouteTableId")
+ subnet_id = _p(p, "SubnetId")
+ rtb = _route_tables.get(rtb_id)
+ if not rtb:
+ return _error("InvalidRouteTableID.NotFound",
+ f"The route table '{rtb_id}' does not exist", 400)
+ assoc_id = "rtbassoc-" + "".join(random.choices(string.hexdigits[:16], k=17))
+ rtb["Associations"].append({
+ "RouteTableAssociationId": assoc_id,
+ "RouteTableId": rtb_id,
+ "SubnetId": subnet_id,
+ "Main": False,
+ "AssociationState": {"State": "associated"},
+ })
+ return _xml(200, "AssociateRouteTableResponse",
+ f"<associationId>{assoc_id}</associationId>")
+
+
+def _disassociate_route_table(p):
+ assoc_id = _p(p, "AssociationId")
+ for rtb in _route_tables.values():
+ rtb["Associations"] = [
+ a for a in rtb["Associations"]
+ if a["RouteTableAssociationId"] != assoc_id
+ ]
+ return _xml(200, "DisassociateRouteTableResponse", "<return>true</return>")
+
+
+def _create_route(p):
+ rtb_id = _p(p, "RouteTableId")
+ rtb = _route_tables.get(rtb_id)
+ if not rtb:
+ return _error("InvalidRouteTableID.NotFound",
+ f"The route table '{rtb_id}' does not exist", 400)
+ dest = _p(p, "DestinationCidrBlock")
+ gw = _p(p, "GatewayId") or _p(p, "NatGatewayId") or _p(p, "InstanceId") or "local"
+ rtb["Routes"].append({
+ "DestinationCidrBlock": dest,
+ "GatewayId": gw,
+ "State": "active",
+ "Origin": "CreateRoute",
+ })
+ return _xml(200, "CreateRouteResponse", "<return>true</return>")
+
+
+def _replace_route(p):
+ rtb_id = _p(p, "RouteTableId")
+ rtb = _route_tables.get(rtb_id)
+ if not rtb:
+ return _error("InvalidRouteTableID.NotFound",
+ f"The route table '{rtb_id}' does not exist", 400)
+ dest = _p(p, "DestinationCidrBlock")
+ gw = _p(p, "GatewayId") or _p(p, "NatGatewayId") or _p(p, "InstanceId") or "local"
+ for route in rtb["Routes"]:
+ if route.get("DestinationCidrBlock") == dest:
+ route["GatewayId"] = gw
+ break
+ return _xml(200, "ReplaceRouteResponse", "<return>true</return>")
+
+
+def _delete_route(p):
+ rtb_id = _p(p, "RouteTableId")
+ rtb = _route_tables.get(rtb_id)
+ if not rtb:
+ return _error("InvalidRouteTableID.NotFound",
+ f"The route table '{rtb_id}' does not exist", 400)
+ dest = _p(p, "DestinationCidrBlock")
+ rtb["Routes"] = [r for r in rtb["Routes"] if r.get("DestinationCidrBlock") != dest]
+ return _xml(200, "DeleteRouteResponse", "<return>true</return>")
+
+
+# ---------------------------------------------------------------------------
+# Network Interfaces (ENI)
+# ---------------------------------------------------------------------------
+
+def _create_network_interface(p):
+ subnet_id = _p(p, "SubnetId") or _DEFAULT_SUBNET_ID
+ description = _p(p, "Description") or ""
+ sg_ids = _parse_member_list(p, "SecurityGroupId")
+ if not sg_ids:
+ sg_ids = [_DEFAULT_SG_ID]
+ eni_id = "eni-" + "".join(random.choices(string.hexdigits[:16], k=17))
+ private_ip = _random_ip("10.0")
+ az = _subnets.get(subnet_id, {}).get("AvailabilityZone", f"{REGION}a")
+ _network_interfaces[eni_id] = {
+ "NetworkInterfaceId": eni_id,
+ "SubnetId": subnet_id,
+ "VpcId": _subnets.get(subnet_id, {}).get("VpcId", _DEFAULT_VPC_ID),
+ "AvailabilityZone": az,
+ "Description": description,
+ "OwnerId": ACCOUNT_ID,
+ "Status": "available",
+ "PrivateIpAddress": private_ip,
+ "InterfaceType": "interface",
+ "SourceDestCheck": True,
+ "MacAddress": ":".join(f"{random.randint(0,255):02x}" for _ in range(6)),
+ "Groups": [
+ {"GroupId": sg, "GroupName": _security_groups.get(sg, {}).get("GroupName", sg)}
+ for sg in sg_ids
+ ],
+ "Attachment": None,
+ }
+ return _xml(200, "CreateNetworkInterfaceResponse",
+ _eni_fields_xml(_network_interfaces[eni_id], tag="networkInterface"))
+
+
+def _delete_network_interface(p):
+ eni_id = _p(p, "NetworkInterfaceId")
+ if eni_id not in _network_interfaces:
+ return _error("InvalidNetworkInterfaceID.NotFound",
+ f"The network interface '{eni_id}' does not exist", 400)
+ del _network_interfaces[eni_id]
+ return _xml(200, "DeleteNetworkInterfaceResponse", "<return>true</return>")
+
+
+def _describe_network_interfaces(p):
+ filter_ids = _parse_member_list(p, "NetworkInterfaceId")
+ items = "".join(
+ _eni_fields_xml(eni)
+ for eni in _network_interfaces.values()
+ if not filter_ids or eni["NetworkInterfaceId"] in filter_ids
+ )
+ return _xml(200, "DescribeNetworkInterfacesResponse",
+ f"<networkInterfaceSet>{items}</networkInterfaceSet>")
+
+
+def _attach_network_interface(p):
+ eni_id = _p(p, "NetworkInterfaceId")
+ instance_id = _p(p, "InstanceId")
+ device_index = _p(p, "DeviceIndex") or "1"
+ eni = _network_interfaces.get(eni_id)
+ if not eni:
+ return _error("InvalidNetworkInterfaceID.NotFound",
+ f"The network interface '{eni_id}' does not exist", 400)
+ attachment_id = "eni-attach-" + "".join(random.choices(string.hexdigits[:16], k=17))
+ eni["Status"] = "in-use"
+ eni["Attachment"] = {
+ "AttachmentId": attachment_id,
+ "InstanceId": instance_id,
+ "DeviceIndex": int(device_index),
+ "Status": "attached",
+ }
+ return _xml(200, "AttachNetworkInterfaceResponse",
+ f"<attachmentId>{attachment_id}</attachmentId>")
+
+
+def _detach_network_interface(p):
+ attachment_id = _p(p, "AttachmentId")
+ for eni in _network_interfaces.values():
+ if eni.get("Attachment", {}) and eni["Attachment"].get("AttachmentId") == attachment_id:
+ eni["Status"] = "available"
+ eni["Attachment"] = None
+ break
+ return _xml(200, "DetachNetworkInterfaceResponse", "<return>true</return>")
+
+
+# ---------------------------------------------------------------------------
+# VPC Endpoints
+# ---------------------------------------------------------------------------
+
+def _create_vpc_endpoint(p):
+ vpc_id = _p(p, "VpcId") or _DEFAULT_VPC_ID
+ service_name = _p(p, "ServiceName") or ""
+ endpoint_type = _p(p, "VpcEndpointType") or "Gateway"
+ vpce_id = "vpce-" + "".join(random.choices(string.hexdigits[:16], k=17))
+ _vpc_endpoints[vpce_id] = {
+ "VpcEndpointId": vpce_id,
+ "VpcEndpointType": endpoint_type,
+ "VpcId": vpc_id,
+ "ServiceName": service_name,
+ "State": "available",
+ "RouteTableIds": _parse_member_list(p, "RouteTableId"),
+ "SubnetIds": _parse_member_list(p, "SubnetId"),
+ "OwnerId": ACCOUNT_ID,
+ }
+ return _xml(200, "CreateVpcEndpointResponse",
+ _vpce_fields_xml(_vpc_endpoints[vpce_id], tag="vpcEndpoint"))
+
+
+def _delete_vpc_endpoints(p):
+ ids = _parse_member_list(p, "VpcEndpointId")
+ for vpce_id in ids:
+ _vpc_endpoints.pop(vpce_id, None)
+ return _xml(200, "DeleteVpcEndpointsResponse", "<unsuccessful/>")
+
+
+def _describe_vpc_endpoints(p):
+ filter_ids = _parse_member_list(p, "VpcEndpointId")
+ items = "".join(
+ _vpce_fields_xml(ep)
+ for ep in _vpc_endpoints.values()
+ if not filter_ids or ep["VpcEndpointId"] in filter_ids
+ )
+ return _xml(200, "DescribeVpcEndpointsResponse",
+ f"<vpcEndpointSet>{items}</vpcEndpointSet>")
+
+
+# ---------------------------------------------------------------------------
+# Availability Zones
+# ---------------------------------------------------------------------------
+
+def _describe_availability_zones(p):
+ azs = [f"{REGION}a", f"{REGION}b", f"{REGION}c"]
+ items = "".join(f"""<item>
+ <zoneName>{az}</zoneName>
+ <zoneState>available</zoneState>
+ <regionName>{REGION}</regionName>
+ <zoneId>{az}</zoneId>
+ </item>""" for az in azs)
+ return _xml(200, "DescribeAvailabilityZonesResponse",
+ f"<availabilityZoneInfo>{items}</availabilityZoneInfo>")
+
+
+# ---------------------------------------------------------------------------
+# Elastic IPs
+# ---------------------------------------------------------------------------
+
+def _allocate_address(p):
+ domain = _p(p, "Domain") or "vpc"
+ allocation_id = f"eipalloc-{new_uuid().replace('-','')[:17]}"
+ public_ip = _random_ip("52.")
+ _addresses[allocation_id] = {
+ "AllocationId": allocation_id,
+ "PublicIp": public_ip,
+ "Domain": domain,
+ "AssociationId": None,
+ "InstanceId": None,
+ "NetworkInterfaceId": None,
+ "PrivateIpAddress": None,
+ }
+ return _xml(200, "AllocateAddressResponse", f"""
+ <publicIp>{public_ip}</publicIp>
+ <domain>{domain}</domain>
+ <allocationId>{allocation_id}</allocationId>""")
+
+
+def _release_address(p):
+ allocation_id = _p(p, "AllocationId")
+ if allocation_id and allocation_id in _addresses:
+ del _addresses[allocation_id]
+ elif allocation_id:
+ return _error("InvalidAllocationID.NotFound",
+ f"The allocation ID '{allocation_id}' does not exist", 400)
+ return _xml(200, "ReleaseAddressResponse", "<return>true</return>")
+
+
+def _associate_address(p):
+ allocation_id = _p(p, "AllocationId")
+ instance_id = _p(p, "InstanceId")
+ addr = _addresses.get(allocation_id)
+ if not addr:
+ return _error("InvalidAllocationID.NotFound",
+ f"The allocation ID '{allocation_id}' does not exist", 400)
+ association_id = f"eipassoc-{new_uuid().replace('-','')[:17]}"
+ addr["AssociationId"] = association_id
+ addr["InstanceId"] = instance_id
+ return _xml(200, "AssociateAddressResponse",
+ f"<return>true</return><associationId>{association_id}</associationId>")
+
+
+def _disassociate_address(p):
+ association_id = _p(p, "AssociationId")
+ for addr in _addresses.values():
+ if addr.get("AssociationId") == association_id:
+ addr["AssociationId"] = None
+ addr["InstanceId"] = None
+ break
+ return _xml(200, "DisassociateAddressResponse", "<return>true</return>")
+
+
+def _describe_addresses(p):
+ filter_ids = _parse_member_list(p, "AllocationId")
+ items = ""
+ for addr in _addresses.values():
+ if filter_ids and addr["AllocationId"] not in filter_ids:
+ continue
+ assoc = f"<associationId>{addr['AssociationId']}</associationId>" if addr["AssociationId"] else ""
+ inst = f"<instanceId>{addr['InstanceId']}</instanceId>" if addr["InstanceId"] else ""
+ items += f"""<item>
+ <allocationId>{addr['AllocationId']}</allocationId>
+ <publicIp>{addr['PublicIp']}</publicIp>
+ <domain>{addr['Domain']}</domain>
+ {assoc}{inst}
+ </item>"""
+ return _xml(200, "DescribeAddressesResponse", f"<addressesSet>{items}</addressesSet>")
+
+
+# ---------------------------------------------------------------------------
+# Tags
+# ---------------------------------------------------------------------------
+
+def _create_tags(p):
+ resource_ids = _parse_member_list(p, "ResourceId")
+ tags = _parse_tags(p)
+ for rid in resource_ids:
+ existing = _tags.setdefault(rid, [])
+ existing_map = {t["Key"]: i for i, t in enumerate(existing)}
+ for tag in tags:
+ idx = existing_map.get(tag["Key"])
+ if idx is not None:
+ existing[idx] = tag
+ else:
+ existing.append(tag)
+ existing_map[tag["Key"]] = len(existing) - 1
+ return _xml(200, "CreateTagsResponse", "<return>true</return>")
+
+
+def _delete_tags(p):
+ resource_ids = _parse_member_list(p, "ResourceId")
+ tags_to_remove = _parse_tags(p)
+ keys_to_remove = {t["Key"] for t in tags_to_remove}
+ for rid in resource_ids:
+ if rid in _tags:
+ _tags[rid] = [t for t in _tags[rid] if t["Key"] not in keys_to_remove]
+ return _xml(200, "DeleteTagsResponse", "<return>true</return>")
+
+
+def _describe_tags(p):
+ items = ""
+ for rid, tag_list in _tags.items():
+ resource_type = _guess_resource_type(rid)
+ for tag in tag_list:
+ items += f"""<item>
+ <resourceId>{rid}</resourceId>
+ <resourceType>{resource_type}</resourceType>
+ <key>{tag['Key']}</key>
+ <value>{tag['Value']}</value>
+ </item>"""
+ return _xml(200, "DescribeTagsResponse", f"<tagSet>{items}</tagSet>")
+
+
+# ---------------------------------------------------------------------------
+# XML helpers
+# ---------------------------------------------------------------------------
+
+def _instance_xml(inst):
+ sgs = "".join(
+ f"""<item><groupId>{sg['GroupId']}</groupId><groupName>{sg['GroupName']}</groupName></item>"""
+ for sg in inst.get("SecurityGroups", [])
+ )
+ tags = "".join(
+ f"<item><key>{t['Key']}</key><value>{t['Value']}</value></item>"
+ for t in _tags.get(inst["InstanceId"], [])
+ )
+ return f"""<item>
+ <instanceId>{inst['InstanceId']}</instanceId>
+ <imageId>{inst['ImageId']}</imageId>
+ <instanceState>
+ <code>{inst['State']['Code']}</code>
+ <name>{inst['State']['Name']}</name>
+ </instanceState>
+ <instanceType>{inst['InstanceType']}</instanceType>
+ <keyName>{inst.get('KeyName','')}</keyName>
+ <launchTime>{inst['LaunchTime']}</launchTime>
+ <placement>
+ <availabilityZone>{inst['Placement']['AvailabilityZone']}</availabilityZone>
+ <tenancy>{inst['Placement']['Tenancy']}</tenancy>
+ </placement>
+ <privateDnsName>{inst['PrivateDnsName']}</privateDnsName>
+ <privateIpAddress>{inst['PrivateIpAddress']}</privateIpAddress>
+ <publicDnsName>{inst['PublicDnsName']}</publicDnsName>
+ <publicIpAddress>{inst['PublicIpAddress']}</publicIpAddress>
+ <subnetId>{inst['SubnetId']}</subnetId>
+ <vpcId>{inst['VpcId']}</vpcId>
+ <architecture>{inst['Architecture']}</architecture>
+ <rootDeviceType>{inst['RootDeviceType']}</rootDeviceType>
+ <rootDeviceName>{inst['RootDeviceName']}</rootDeviceName>
+ <virtualizationType>{inst['Virtualization']}</virtualizationType>
+ <hypervisor>{inst['Hypervisor']}</hypervisor>
+ <monitoring><state>{inst['Monitoring']['State']}</state></monitoring>
+ <groupSet>{sgs}</groupSet>
+ <tagSet>{tags}</tagSet>
+ <amiLaunchIndex>{inst['AmiLaunchIndex']}</amiLaunchIndex>
+ </item>"""
+
+
+def _sg_xml(sg):
+ ingress = "".join(_perm_xml(r) for r in sg.get("IpPermissions", []))
+ egress = "".join(_perm_xml(r) for r in sg.get("IpPermissionsEgress", []))
+ return f"""<item>
+ <ownerId>{sg['OwnerId']}</ownerId>
+ <groupId>{sg['GroupId']}</groupId>
+ <groupName>{sg['GroupName']}</groupName>
+ <groupDescription>{sg['Description']}</groupDescription>
+ <vpcId>{sg['VpcId']}</vpcId>
+ <ipPermissions>{ingress}</ipPermissions>
+ <ipPermissionsEgress>{egress}</ipPermissionsEgress>
+ <tagSet/>
+ </item>"""
+
+
+def _perm_xml(r):
+ ranges = "".join(
+ f"<item><cidrIp>{ip['CidrIp']}</cidrIp></item>"
+ for ip in r.get("IpRanges", [])
+ )
+ from_port = f"<fromPort>{r['FromPort']}</fromPort>" if "FromPort" in r else ""
+ to_port = f"<toPort>{r['ToPort']}</toPort>" if "ToPort" in r else ""
+ return f"""<item>
+ <ipProtocol>{r.get('IpProtocol','-1')}</ipProtocol>
+ {from_port}{to_port}
+ <ipRanges>{ranges}</ipRanges>
+ <ipv6Ranges/><prefixListIds/><groups/>
+ </item>"""
+
+
+def _vpc_fields_xml(vpc, tag="item"):
+ return f"""<{tag}>
+ <vpcId>{vpc['VpcId']}</vpcId>
+ <state>{vpc['State']}</state>
+ <cidrBlock>{vpc['CidrBlock']}</cidrBlock>
+ <dhcpOptionsId>{vpc['DhcpOptionsId']}</dhcpOptionsId>
+ <instanceTenancy>{vpc['InstanceTenancy']}</instanceTenancy>
+ <isDefault>{'true' if vpc['IsDefault'] else 'false'}</isDefault>
+ <ownerId>{vpc['OwnerId']}</ownerId>
+ <tagSet/>
+ </{tag}>"""
+
+
+def _vpc_xml(vpc):
+ return _vpc_fields_xml(vpc, tag="item")
+
+
+def _subnet_fields_xml(subnet, tag="item"):
+ return f"""<{tag}>
+ <subnetId>{subnet['SubnetId']}</subnetId>
+ <subnetArn>arn:aws:ec2:{REGION}:{ACCOUNT_ID}:subnet/{subnet['SubnetId']}</subnetArn>
+ <state>{subnet['State']}</state>
+ <vpcId>{subnet['VpcId']}</vpcId>
+ <cidrBlock>{subnet['CidrBlock']}</cidrBlock>
+ <availableIpAddressCount>{subnet['AvailableIpAddressCount']}</availableIpAddressCount>
+ <availabilityZone>{subnet['AvailabilityZone']}</availabilityZone>
+ <defaultForAz>{'true' if subnet['DefaultForAz'] else 'false'}</defaultForAz>
+ <mapPublicIpOnLaunch>{'true' if subnet['MapPublicIpOnLaunch'] else 'false'}</mapPublicIpOnLaunch>
+ <ownerId>{subnet['OwnerId']}</ownerId>
+ <tagSet/>
+ </{tag}>"""
+
+
+def _subnet_xml(subnet):
+ return _subnet_fields_xml(subnet, tag="item")
+
+
+def _igw_fields_xml(igw, tag="item"):
+ attachments = "".join(
+ f"<item><vpcId>{a['VpcId']}</vpcId><state>{a['State']}</state></item>"
+ for a in igw.get("Attachments", [])
+ )
+ return f"""<{tag}>
+ <internetGatewayId>{igw['InternetGatewayId']}</internetGatewayId>
+ <ownerId>{igw['OwnerId']}</ownerId>
+ <attachmentSet>{attachments}</attachmentSet>
+ <tagSet/>
+ </{tag}>"""
+
+
+def _igw_xml(igw):
+ return _igw_fields_xml(igw, tag="item")
+
+
+def _rtb_fields_xml(rtb, tag="item"):
+ routes = "".join(f"""<item>
+ <destinationCidrBlock>{r.get('DestinationCidrBlock','')}</destinationCidrBlock>
+ <gatewayId>{r.get('GatewayId','')}</gatewayId>
+ <state>{r.get('State','active')}</state>
+ <origin>{r.get('Origin','')}</origin>
+ </item>""" for r in rtb.get("Routes", []))
+ assocs = "".join(f"""<item>
+ <routeTableAssociationId>{a['RouteTableAssociationId']}</routeTableAssociationId>
+ <routeTableId>{a['RouteTableId']}</routeTableId>
+ <main>{'true' if a.get('Main') else 'false'}</main>
+ {'<subnetId>' + a['SubnetId'] + '</subnetId>' if a.get('SubnetId') else ''}
+ </item>""" for a in rtb.get("Associations", []))
+ return f"""<{tag}>
+ <routeTableId>{rtb['RouteTableId']}</routeTableId>
+ <vpcId>{rtb['VpcId']}</vpcId>
+ <ownerId>{rtb['OwnerId']}</ownerId>
+ <routeSet>{routes}</routeSet>
+ <associationSet>{assocs}</associationSet>
+ <propagatingVgwSet/>
+ <tagSet/>
+ </{tag}>"""
+
+
+def _eni_fields_xml(eni, tag="item"):
+ groups = "".join(
+ f"<item><groupId>{g['GroupId']}</groupId><groupName>{g['GroupName']}</groupName></item>"
+ for g in eni.get("Groups", [])
+ )
+ attachment = ""
+ if eni.get("Attachment"):
+ a = eni["Attachment"]
+ attachment = f"""<attachment>
+ <attachmentId>{a['AttachmentId']}</attachmentId>
+ <instanceId>{a.get('InstanceId','')}</instanceId>
+ <deviceIndex>{a.get('DeviceIndex',0)}</deviceIndex>
+ <status>{a.get('Status','attached')}</status>
+ </attachment>"""
+ private_ip = eni['PrivateIpAddress']
+ return f"""<{tag}>
+ <networkInterfaceId>{eni['NetworkInterfaceId']}</networkInterfaceId>
+ <subnetId>{eni['SubnetId']}</subnetId>
+ <vpcId>{eni['VpcId']}</vpcId>
+ <availabilityZone>{eni.get('AvailabilityZone', REGION + 'a')}</availabilityZone>
+ <description>{eni['Description']}</description>
+ <ownerId>{eni['OwnerId']}</ownerId>
+ <status>{eni['Status']}</status>
+ <privateIpAddress>{private_ip}</privateIpAddress>
+ <sourceDestCheck>{'true' if eni.get('SourceDestCheck', True) else 'false'}</sourceDestCheck>
+ <interfaceType>{eni.get('InterfaceType', 'interface')}</interfaceType>
+ <macAddress>{eni['MacAddress']}</macAddress>
+ <groupSet>{groups}</groupSet>
+ <privateIpAddressesSet>
+ <item>
+ <privateIpAddress>{private_ip}</privateIpAddress>
+ <primary>true</primary>
+ </item>
+ </privateIpAddressesSet>
+ {attachment}
+ <tagSet/>
+ </{tag}>"""
+
+
+def _vpce_fields_xml(ep, tag="item"):
+ rtb_ids = "".join(f"<item>{r}</item>" for r in ep.get("RouteTableIds", []))
+ subnet_ids = "".join(f"<item>{s}</item>" for s in ep.get("SubnetIds", []))
+ return f"""<{tag}>
+ <vpcEndpointId>{ep['VpcEndpointId']}</vpcEndpointId>
+ <vpcEndpointType>{ep['VpcEndpointType']}</vpcEndpointType>
+ <vpcId>{ep['VpcId']}</vpcId>
+ <serviceName>{ep['ServiceName']}</serviceName>
+ <state>{ep['State']}</state>
+ <ownerId>{ep['OwnerId']}</ownerId>
+ <routeTableIdSet>{rtb_ids}</routeTableIdSet>
+ <subnetIdSet>{subnet_ids}</subnetIdSet>
+ <tagSet/>
+ </{tag}>"""
+
+
+# ---------------------------------------------------------------------------
+# Parse helpers
+# ---------------------------------------------------------------------------
+
+def _p(params, key, default=""):
+ val = params.get(key, [default])
+ if isinstance(val, list):
+ return val[0] if val else default
+ return val
+
+
+def _parse_member_list(params, prefix):
+ items = []
+ i = 1
+ while True:
+ val = _p(params, f"{prefix}.{i}")
+ if not val:
+ break
+ items.append(val)
+ i += 1
+ return items
+
+
+def _parse_tags(params):
+ tags = []
+ i = 1
+ while True:
+ key = _p(params, f"Tag.{i}.Key")
+ if not key:
+ break
+ tags.append({"Key": key, "Value": _p(params, f"Tag.{i}.Value", "")})
+ i += 1
+ return tags
+
+
+def _parse_filters(params):
+ filters = {}
+ i = 1
+ while True:
+ name = _p(params, f"Filter.{i}.Name")
+ if not name:
+ break
+ vals = []
+ j = 1
+ while True:
+ v = _p(params, f"Filter.{i}.Value.{j}")
+ if not v:
+ break
+ vals.append(v)
+ j += 1
+ filters[name] = vals
+ i += 1
+ return filters
+
+
+def _matches_filters(inst, filters):
+ for name, vals in filters.items():
+ if name == "instance-state-name":
+ if inst["State"]["Name"] not in vals:
+ return False
+ elif name == "instance-type":
+ if inst["InstanceType"] not in vals:
+ return False
+ elif name == "image-id":
+ if inst["ImageId"] not in vals:
+ return False
+ return True
+
+
+def _parse_ip_permissions(params, prefix):
+ rules = []
+ i = 1
+ while True:
+ proto = _p(params, f"{prefix}.{i}.IpProtocol")
+ if not proto:
+ break
+ rule = {"IpProtocol": proto, "IpRanges": [], "Ipv6Ranges": [],
+ "PrefixListIds": [], "UserIdGroupPairs": []}
+ from_port = _p(params, f"{prefix}.{i}.FromPort")
+ to_port = _p(params, f"{prefix}.{i}.ToPort")
+ if from_port:
+ rule["FromPort"] = int(from_port)
+ if to_port:
+ rule["ToPort"] = int(to_port)
+ j = 1
+ while True:
+ cidr = _p(params, f"{prefix}.{i}.IpRanges.{j}.CidrIp")
+ if not cidr:
+ break
+ rule["IpRanges"].append({"CidrIp": cidr})
+ j += 1
+ rules.append(rule)
+ i += 1
+ return rules
+
+
+# ---------------------------------------------------------------------------
+# ID generators
+# ---------------------------------------------------------------------------
+
+def _new_instance_id():
+ return "i-" + "".join(random.choices(string.hexdigits[:16], k=17))
+
+
+def _new_sg_id():
+ return "sg-" + "".join(random.choices(string.hexdigits[:16], k=17))
+
+
+def _new_vpc_id():
+ return "vpc-" + "".join(random.choices(string.hexdigits[:16], k=17))
+
+
+def _new_subnet_id():
+ return "subnet-" + "".join(random.choices(string.hexdigits[:16], k=17))
+
+
+def _new_igw_id():
+ return "igw-" + "".join(random.choices(string.hexdigits[:16], k=17))
+
+
+def _random_ip(prefix):
+ return f"{prefix}{random.randint(1,254)}.{random.randint(1,254)}"
+
+
+def _now_ts():
+ return time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime())
+
+
+def _guess_resource_type(resource_id):
+ if resource_id.startswith("i-"):
+ return "instance"
+ if resource_id.startswith("sg-"):
+ return "security-group"
+ if resource_id.startswith("vpc-"):
+ return "vpc"
+ if resource_id.startswith("subnet-"):
+ return "subnet"
+ if resource_id.startswith("igw-"):
+ return "internet-gateway"
+ if resource_id.startswith("eipalloc-"):
+ return "elastic-ip"
+ if resource_id.startswith("rtb-"):
+ return "route-table"
+ if resource_id.startswith("eni-"):
+ return "network-interface"
+ if resource_id.startswith("vpce-"):
+ return "vpc-endpoint"
+ return "resource"
+
+
+# ---------------------------------------------------------------------------
+# XML response builders
+# ---------------------------------------------------------------------------
+
+def _xml(status, root_tag, inner):
+ from ministack.core.responses import new_uuid as _uuid
+ body = f"""<?xml version="1.0" encoding="UTF-8"?>
+<{root_tag} xmlns="http://ec2.amazonaws.com/doc/2016-11-15/">
+ {inner}
+ <requestId>{_uuid()}</requestId>
+</{root_tag}>""".encode("utf-8")
+ return status, {"Content-Type": "application/xml"}, body
+
+
+def _error(code, message, status):
+ from ministack.core.responses import new_uuid as _uuid
+ body = f"""<?xml version="1.0" encoding="UTF-8"?>
+<Response>
+ <Errors><Error>
+ <Code>{code}</Code>
+ <Message>{message}</Message>
+ </Error></Errors>
+ <RequestID>{_uuid()}</RequestID>
+</Response>""".encode("utf-8")
+ return status, {"Content-Type": "application/xml"}, body
+
+
+# ---------------------------------------------------------------------------
+# Reset
+# ---------------------------------------------------------------------------
+
+def reset():
+ _instances.clear()
+ _security_groups.clear()
+ _key_pairs.clear()
+ _vpcs.clear()
+ _subnets.clear()
+ _internet_gateways.clear()
+ _addresses.clear()
+ _tags.clear()
+ _route_tables.clear()
+ _network_interfaces.clear()
+ _vpc_endpoints.clear()
+ _init_defaults()
+
+
+# ---------------------------------------------------------------------------
+# Action map
+# ---------------------------------------------------------------------------
+
+_ACTION_MAP = {
+ "RunInstances": _run_instances,
+ "DescribeInstances": _describe_instances,
+ "TerminateInstances": _terminate_instances,
+ "StopInstances": _stop_instances,
+ "StartInstances": _start_instances,
+ "RebootInstances": _reboot_instances,
+ "DescribeImages": _describe_images,
+ "CreateSecurityGroup": _create_security_group,
+ "DeleteSecurityGroup": _delete_security_group,
+ "DescribeSecurityGroups": _describe_security_groups,
+ "AuthorizeSecurityGroupIngress": _authorize_sg_ingress,
+ "RevokeSecurityGroupIngress": _revoke_sg_ingress,
+ "AuthorizeSecurityGroupEgress": _authorize_sg_egress,
+ "RevokeSecurityGroupEgress": _revoke_sg_egress,
+ "CreateKeyPair": _create_key_pair,
+ "DeleteKeyPair": _delete_key_pair,
+ "DescribeKeyPairs": _describe_key_pairs,
+ "ImportKeyPair": _import_key_pair,
+ "DescribeVpcs": _describe_vpcs,
+ "CreateVpc": _create_vpc,
+ "DeleteVpc": _delete_vpc,
+ "DescribeSubnets": _describe_subnets,
+ "CreateSubnet": _create_subnet,
+ "DeleteSubnet": _delete_subnet,
+ "CreateInternetGateway": _create_internet_gateway,
+ "DeleteInternetGateway": _delete_internet_gateway,
+ "DescribeInternetGateways": _describe_internet_gateways,
+ "AttachInternetGateway": _attach_internet_gateway,
+ "DetachInternetGateway": _detach_internet_gateway,
+ "DescribeAvailabilityZones": _describe_availability_zones,
+ "AllocateAddress": _allocate_address,
+ "ReleaseAddress": _release_address,
+ "AssociateAddress": _associate_address,
+ "DisassociateAddress": _disassociate_address,
+ "DescribeAddresses": _describe_addresses,
+ "CreateTags": _create_tags,
+ "DeleteTags": _delete_tags,
+ "DescribeTags": _describe_tags,
+ "ModifyVpcAttribute": _modify_vpc_attribute,
+ "ModifySubnetAttribute": _modify_subnet_attribute,
+ "CreateRouteTable": _create_route_table,
+ "DeleteRouteTable": _delete_route_table,
+ "DescribeRouteTables": _describe_route_tables,
+ "AssociateRouteTable": _associate_route_table,
+ "DisassociateRouteTable": _disassociate_route_table,
+ "CreateRoute": _create_route,
+ "ReplaceRoute": _replace_route,
+ "DeleteRoute": _delete_route,
+ "CreateNetworkInterface": _create_network_interface,
+ "DeleteNetworkInterface": _delete_network_interface,
+ "DescribeNetworkInterfaces": _describe_network_interfaces,
+ "AttachNetworkInterface": _attach_network_interface,
+ "DetachNetworkInterface": _detach_network_interface,
+ "CreateVpcEndpoint": _create_vpc_endpoint,
+ "DeleteVpcEndpoints": _delete_vpc_endpoints,
+ "DescribeVpcEndpoints": _describe_vpc_endpoints,
+}
diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.py
index e12e01ac..a0f13d40 100644
--- a/ministack/services/stepfunctions.py
+++ b/ministack/services/stepfunctions.py
@@ -8,6 +8,8 @@ Supports: CreateStateMachine, DeleteStateMachine, DescribeStateMachine,
DescribeExecution, DescribeStateMachineForExecution, ListExecutions,
GetExecutionHistory,
SendTaskSuccess, SendTaskFailure, SendTaskHeartbeat,
+ CreateActivity, DeleteActivity, DescribeActivity, ListActivities,
+ GetActivityTask,
TagResource, UntagResource, ListTagsForResource.
ASL state types: Pass, Task, Choice, Wait, Succeed, Fail, Parallel, Map.
@@ -37,6 +39,8 @@ _state_machines: dict = {}
_executions: dict = {}
_task_tokens: dict = {}
_tags: dict = {}
+_activities: dict = {}
+_activity_tasks: dict = {}
# ---------------------------------------------------------------------------
@@ -71,11 +75,18 @@ async def handle_request(method, path, headers, body, query_params):
"ListTagsForResource": _list_tags_for_resource,
"StartSyncExecution": _start_sync_execution,
"DescribeStateMachineForExecution": _describe_state_machine_for_execution,
+ "CreateActivity": _create_activity,
+ "DeleteActivity": _delete_activity,
+ "DescribeActivity": _describe_activity,
+ "ListActivities": _list_activities,
+ "GetActivityTask": _get_activity_task,
}
handler = handlers.get(action)
if not handler:
return error_response_json("InvalidAction", f"Unknown action: {action}", 400)
+ if action == "GetActivityTask":
+ return await _get_activity_task(data)
return handler(data)
@@ -399,6 +410,76 @@ def _send_task_heartbeat(data):
return json_response({})
+# ---------------------------------------------------------------------------
+# Activity CRUD
+# ---------------------------------------------------------------------------
+
+def _create_activity(data):
+ name = data.get("name")
+ if not name:
+ return error_response_json("ValidationException", "name is required", 400)
+
+ arn = f"arn:aws:states:{REGION}:{ACCOUNT_ID}:activity:{name}"
+ if arn in _activities:
+ return error_response_json(
+ "ActivityAlreadyExists", f"Activity already exists: {arn}", 400)
+
+ ts = now_iso()
+ _activities[arn] = {"activityArn": arn, "name": name, "creationDate": ts}
+ _activity_tasks[arn] = []
+
+ tags = data.get("tags", [])
+ if tags:
+ _tags[arn] = list(tags)
+
+ return json_response({"activityArn": arn, "creationDate": ts})
+
+
+def _delete_activity(data):
+ arn = data.get("activityArn")
+ if arn not in _activities:
+ return error_response_json(
+ "ActivityDoesNotExist", f"Activity {arn} not found", 400)
+ del _activities[arn]
+ _activity_tasks.pop(arn, None)
+ _tags.pop(arn, None)
+ return json_response({})
+
+
+def _describe_activity(data):
+ arn = data.get("activityArn")
+ act = _activities.get(arn)
+ if not act:
+ return error_response_json(
+ "ActivityDoesNotExist", f"Activity {arn} not found", 400)
+ return json_response(act)
+
+
+def _list_activities(data):
+ acts = [
+ {"activityArn": a["activityArn"], "name": a["name"], "creationDate": a["creationDate"]}
+ for a in _activities.values()
+ ]
+ return json_response({"activities": acts})
+
+
+async def _get_activity_task(data):
+ arn = data.get("activityArn")
+ if arn not in _activities:
+ return error_response_json(
+ "ActivityDoesNotExist", f"Activity {arn} not found", 400)
+
+ queue = _activity_tasks.get(arn, [])
+ deadline = time.monotonic() + 60
+ while time.monotonic() < deadline:
+ if queue:
+ task = queue.pop(0)
+ return json_response({"taskToken": task["taskToken"], "input": task["input"]})
+ await asyncio.sleep(0.5)
+
+ return json_response({})
+
+
# ---------------------------------------------------------------------------
# Tagging
# ---------------------------------------------------------------------------
@@ -700,6 +781,10 @@ def _invoke_resource(resource, input_data):
if func_name:
return _call_lambda(func_name, input_data)
+ # Activity resource — enqueue task and wait for worker to call GetActivityTask + SendTask*
+ if ":activity:" in resource:
+ return _invoke_activity(resource, input_data)
+
# Service integration dispatch
clean = resource.replace(".sync", "").replace(".waitForTaskToken", "")
for prefix, handler in _SERVICE_DISPATCH.items():
@@ -709,6 +794,38 @@ def _invoke_resource(resource, input_data):
return input_data
+def _invoke_activity(resource, input_data):
+ """Enqueue a task for the activity worker and block until SendTaskSuccess/Failure."""
+ arn = resource
+ if arn not in _activities:
+ raise _ExecutionError(
+ "ActivityDoesNotExist", f"Activity {arn} not found")
+
+ token = new_uuid()
+ evt = threading.Event()
+ _task_tokens[token] = {"event": evt, "result": None, "error": None, "heartbeat": None}
+
+ _activity_tasks[arn].append({
+ "taskToken": token,
+ "input": json.dumps(input_data),
+ })
+
+ timeout = 99999
+ if not evt.wait(timeout=timeout):
+ _task_tokens.pop(token, None)
+ raise _ExecutionError("States.Timeout", "Activity task timed out waiting for worker")
+
+ info = _task_tokens.pop(token, {})
+ if info.get("error"):
+ e = info["error"]
+ raise _ExecutionError(e.get("Error", "TaskFailed"), e.get("Cause", ""))
+ result_raw = info.get("result", "{}")
+ try:
+ return json.loads(result_raw) if isinstance(result_raw, str) else result_raw
+ except json.JSONDecodeError:
+ return result_raw
+
+
def _invoke_with_callback(resource, input_data, token, state_def):
"""waitForTaskToken pattern: invoke then block until callback."""
evt = threading.Event()
@@ -1363,3 +1480,5 @@ def reset():
_executions.clear()
_task_tokens.clear()
_tags.clear()
+ _activities.clear()
+ _activity_tasks.clear()
diff --git a/pyproject.toml b/pyproject.toml
index 0d6b4279..068d54ff 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "ministack"
-version = "1.1.0"
+version = "1.1.1"
description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"
readme = "README.md"
license = { file = "LICENSE" }
diff --git a/tests/conftest.py b/tests/conftest.py
index 728994d3..46e4a663 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -141,6 +141,10 @@ def cognito_idp():
def cognito_identity():
return make_client("cognito-identity")
[email protected](scope="session")
+def ec2():
+ return make_client("ec2")
+
@pytest.fixture(scope="session")
def sfn_sync():
"""SFN client for StartSyncExecution — forces same endpoint (boto3 normally prefixes sync-)."""
diff --git a/tests/test_services.py b/tests/test_services.py
index 23aa24ff..68b6303d 100644
--- a/tests/test_services.py
+++ b/tests/test_services.py
@@ -10631,3 +10631,488 @@ def test_ses_configuration_set_crud(ses):
ses.delete_configuration_set(ConfigurationSetName="qa-ses-config")
sets2 = ses.list_configuration_sets()["ConfigurationSets"]
assert not any(s["Name"] == "qa-ses-config" for s in sets2)
+
+
+# ---------------------------------------------------------------------------
+# SFN Activities
+# ---------------------------------------------------------------------------
+
+def test_sfn_activity_create_describe_delete(sfn):
+ resp = sfn.create_activity(name="qa-act-crud")
+ arn = resp["activityArn"]
+ assert ":activity:qa-act-crud" in arn
+
+ desc = sfn.describe_activity(activityArn=arn)
+ assert desc["name"] == "qa-act-crud"
+ assert desc["activityArn"] == arn
+
+ sfn.delete_activity(activityArn=arn)
+ with pytest.raises(ClientError) as exc:
+ sfn.describe_activity(activityArn=arn)
+ assert exc.value.response["Error"]["Code"] == "ActivityDoesNotExist"
+
+
+def test_sfn_activity_list(sfn):
+ sfn.create_activity(name="qa-act-list-1")
+ sfn.create_activity(name="qa-act-list-2")
+ acts = sfn.list_activities()["activities"]
+ names = [a["name"] for a in acts]
+ assert "qa-act-list-1" in names
+ assert "qa-act-list-2" in names
+
+
+def test_sfn_activity_create_already_exists(sfn):
+ sfn.create_activity(name="qa-act-idem")
+ with pytest.raises(ClientError) as exc:
+ sfn.create_activity(name="qa-act-idem")
+ assert exc.value.response["Error"]["Code"] == "ActivityAlreadyExists"
+
+
+def test_sfn_activity_worker_flow(sfn):
+ """Worker calls GetActivityTask, then SendTaskSuccess — execution succeeds."""
+ import threading
+
+ act_arn = sfn.create_activity(name="qa-act-worker")["activityArn"]
+
+ definition = json.dumps({
+ "StartAt": "DoWork",
+ "States": {
+ "DoWork": {"Type": "Task", "Resource": act_arn, "End": True},
+ },
+ })
+ sm_arn = sfn.create_state_machine(
+ name="qa-sfn-act-worker",
+ definition=definition,
+ roleArn="arn:aws:iam::000000000000:role/r",
+ )["stateMachineArn"]
+
+ exec_arn = sfn.start_execution(
+ stateMachineArn=sm_arn, input=json.dumps({"msg": "hello"})
+ )["executionArn"]
+
+ def worker():
+ task = sfn.get_activity_task(activityArn=act_arn, workerName="test-worker")
+ assert task["taskToken"] != ""
+ assert json.loads(task["input"])["msg"] == "hello"
+ sfn.send_task_success(
+ taskToken=task["taskToken"],
+ output=json.dumps({"result": "done"}),
+ )
+
+ t = threading.Thread(target=worker, daemon=True)
+ t.start()
+ t.join(timeout=10)
+
+ for _ in range(20):
+ time.sleep(0.3)
+ status = sfn.describe_execution(executionArn=exec_arn)["status"]
+ if status != "RUNNING":
+ break
+
+ assert sfn.describe_execution(executionArn=exec_arn)["status"] == "SUCCEEDED"
+ output = json.loads(sfn.describe_execution(executionArn=exec_arn)["output"])
+ assert output["result"] == "done"
+
+
+def test_sfn_activity_worker_failure(sfn):
+ """Worker calls GetActivityTask then SendTaskFailure — execution fails."""
+ import threading
+
+ act_arn = sfn.create_activity(name="qa-act-fail")["activityArn"]
+
+ definition = json.dumps({
+ "StartAt": "DoWork",
+ "States": {
+ "DoWork": {"Type": "Task", "Resource": act_arn, "End": True},
+ },
+ })
+ sm_arn = sfn.create_state_machine(
+ name="qa-sfn-act-fail",
+ definition=definition,
+ roleArn="arn:aws:iam::000000000000:role/r",
+ )["stateMachineArn"]
+
+ exec_arn = sfn.start_execution(
+ stateMachineArn=sm_arn, input="{}"
+ )["executionArn"]
+
+ def worker():
+ task = sfn.get_activity_task(activityArn=act_arn, workerName="test-worker")
+ sfn.send_task_failure(
+ taskToken=task["taskToken"],
+ error="WorkerError",
+ cause="something went wrong",
+ )
+
+ t = threading.Thread(target=worker, daemon=True)
+ t.start()
+ t.join(timeout=10)
+
+ for _ in range(20):
+ time.sleep(0.3)
+ status = sfn.describe_execution(executionArn=exec_arn)["status"]
+ if status != "RUNNING":
+ break
+
+ assert sfn.describe_execution(executionArn=exec_arn)["status"] == "FAILED"
+
+
+# ---------------------------------------------------------------------------
+# EC2
+# ---------------------------------------------------------------------------
+
+def test_ec2_describe_vpcs_default(ec2):
+ resp = ec2.describe_vpcs()
+ vpcs = resp["Vpcs"]
+ assert any(v["IsDefault"] for v in vpcs)
+
+
+def test_ec2_describe_subnets_default(ec2):
+ resp = ec2.describe_subnets()
+ assert len(resp["Subnets"]) >= 1
+
+
+def test_ec2_describe_availability_zones(ec2):
+ resp = ec2.describe_availability_zones()
+ azs = [az["ZoneName"] for az in resp["AvailabilityZones"]]
+ assert any("us-east-1" in az for az in azs)
+
+
+def test_ec2_run_describe_terminate_instances(ec2):
+ resp = ec2.run_instances(ImageId="ami-00000000", MinCount=1, MaxCount=1,
+ InstanceType="t2.micro")
+ assert len(resp["Instances"]) == 1
+ instance_id = resp["Instances"][0]["InstanceId"]
+ assert instance_id.startswith("i-")
+ assert resp["Instances"][0]["State"]["Name"] == "running"
+
+ desc = ec2.describe_instances(InstanceIds=[instance_id])
+ assert len(desc["Reservations"]) == 1
+ assert desc["Reservations"][0]["Instances"][0]["InstanceId"] == instance_id
+
+ term = ec2.terminate_instances(InstanceIds=[instance_id])
+ assert term["TerminatingInstances"][0]["CurrentState"]["Name"] == "terminated"
+
+
+def test_ec2_stop_start_instances(ec2):
+ resp = ec2.run_instances(ImageId="ami-00000000", MinCount=1, MaxCount=1)
+ iid = resp["Instances"][0]["InstanceId"]
+
+ stop = ec2.stop_instances(InstanceIds=[iid])
+ assert stop["StoppingInstances"][0]["CurrentState"]["Name"] == "stopped"
+
+ start = ec2.start_instances(InstanceIds=[iid])
+ assert start["StartingInstances"][0]["CurrentState"]["Name"] == "running"
+
+ ec2.terminate_instances(InstanceIds=[iid])
+
+
+def test_ec2_run_multiple_instances(ec2):
+ resp = ec2.run_instances(ImageId="ami-00000000", MinCount=3, MaxCount=3)
+ assert len(resp["Instances"]) == 3
+ ids = [i["InstanceId"] for i in resp["Instances"]]
+ assert len(set(ids)) == 3
+ ec2.terminate_instances(InstanceIds=ids)
+
+
+def test_ec2_describe_images(ec2):
+ resp = ec2.describe_images(Owners=["self"])
+ assert len(resp["Images"]) >= 1
+ assert all("ImageId" in img for img in resp["Images"])
+
+
+def test_ec2_security_group_crud(ec2):
+ sg_id = ec2.create_security_group(
+ GroupName="qa-ec2-sg", Description="test sg"
+ )["GroupId"]
+ assert sg_id.startswith("sg-")
+
+ desc = ec2.describe_security_groups(GroupIds=[sg_id])
+ assert desc["SecurityGroups"][0]["GroupName"] == "qa-ec2-sg"
+
+ ec2.delete_security_group(GroupId=sg_id)
+ desc2 = ec2.describe_security_groups()
+ assert not any(sg["GroupId"] == sg_id for sg in desc2["SecurityGroups"])
+
+
+def test_ec2_security_group_duplicate(ec2):
+ ec2.create_security_group(GroupName="qa-ec2-sg-dup", Description="d")
+ with pytest.raises(ClientError) as exc:
+ ec2.create_security_group(GroupName="qa-ec2-sg-dup", Description="d")
+ assert exc.value.response["Error"]["Code"] == "InvalidGroup.Duplicate"
+
+
+def test_ec2_sg_authorize_revoke_ingress(ec2):
+ sg_id = ec2.create_security_group(
+ GroupName="qa-ec2-sg-rules", Description="rules test"
+ )["GroupId"]
+
+ ec2.authorize_security_group_ingress(
+ GroupId=sg_id,
+ IpPermissions=[{"IpProtocol": "tcp", "FromPort": 80, "ToPort": 80,
+ "IpRanges": [{"CidrIp": "0.0.0.0/0"}]}],
+ )
+ desc = ec2.describe_security_groups(GroupIds=[sg_id])
+ perms = desc["SecurityGroups"][0]["IpPermissions"]
+ assert any(p["FromPort"] == 80 for p in perms)
+
+ ec2.revoke_security_group_ingress(
+ GroupId=sg_id,
+ IpPermissions=[{"IpProtocol": "tcp", "FromPort": 80, "ToPort": 80,
+ "IpRanges": [{"CidrIp": "0.0.0.0/0"}]}],
+ )
+ desc2 = ec2.describe_security_groups(GroupIds=[sg_id])
+ assert not any(p.get("FromPort") == 80
+ for p in desc2["SecurityGroups"][0]["IpPermissions"])
+
+ ec2.delete_security_group(GroupId=sg_id)
+
+
+def test_ec2_key_pair_crud(ec2):
+ resp = ec2.create_key_pair(KeyName="qa-ec2-key")
+ assert resp["KeyName"] == "qa-ec2-key"
+ assert "KeyMaterial" in resp
+
+ desc = ec2.describe_key_pairs(KeyNames=["qa-ec2-key"])
+ assert len(desc["KeyPairs"]) == 1
+
+ ec2.delete_key_pair(KeyName="qa-ec2-key")
+ desc2 = ec2.describe_key_pairs()
+ assert not any(kp["KeyName"] == "qa-ec2-key" for kp in desc2["KeyPairs"])
+
+
+def test_ec2_key_pair_duplicate(ec2):
+ ec2.create_key_pair(KeyName="qa-ec2-key-dup")
+ with pytest.raises(ClientError) as exc:
+ ec2.create_key_pair(KeyName="qa-ec2-key-dup")
+ assert exc.value.response["Error"]["Code"] == "InvalidKeyPair.Duplicate"
+
+
+def test_ec2_vpc_create_delete(ec2):
+ vpc_id = ec2.create_vpc(CidrBlock="10.1.0.0/16")["Vpc"]["VpcId"]
+ assert vpc_id.startswith("vpc-")
+
+ desc = ec2.describe_vpcs(VpcIds=[vpc_id])
+ assert desc["Vpcs"][0]["CidrBlock"] == "10.1.0.0/16"
+ assert not desc["Vpcs"][0]["IsDefault"]
+
+ ec2.delete_vpc(VpcId=vpc_id)
+ desc2 = ec2.describe_vpcs()
+ assert not any(v["VpcId"] == vpc_id for v in desc2["Vpcs"])
+
+
+def test_ec2_subnet_create_delete(ec2):
+ vpc_id = ec2.create_vpc(CidrBlock="10.2.0.0/16")["Vpc"]["VpcId"]
+ subnet_id = ec2.create_subnet(
+ VpcId=vpc_id, CidrBlock="10.2.1.0/24"
+ )["Subnet"]["SubnetId"]
+ assert subnet_id.startswith("subnet-")
+
+ desc = ec2.describe_subnets(SubnetIds=[subnet_id])
+ assert desc["Subnets"][0]["CidrBlock"] == "10.2.1.0/24"
+
+ ec2.delete_subnet(SubnetId=subnet_id)
+ ec2.delete_vpc(VpcId=vpc_id)
+
+
+def test_ec2_internet_gateway_crud(ec2):
+ igw_id = ec2.create_internet_gateway()["InternetGateway"]["InternetGatewayId"]
+ assert igw_id.startswith("igw-")
+
+ vpc_id = ec2.create_vpc(CidrBlock="10.3.0.0/16")["Vpc"]["VpcId"]
+ ec2.attach_internet_gateway(InternetGatewayId=igw_id, VpcId=vpc_id)
+
+ desc = ec2.describe_internet_gateways(InternetGatewayIds=[igw_id])
+ assert len(desc["InternetGateways"][0]["Attachments"]) == 1
+
+ ec2.detach_internet_gateway(InternetGatewayId=igw_id, VpcId=vpc_id)
+ ec2.delete_internet_gateway(InternetGatewayId=igw_id)
+ ec2.delete_vpc(VpcId=vpc_id)
+
+
+def test_ec2_elastic_ip_crud(ec2):
+ alloc = ec2.allocate_address(Domain="vpc")
+ alloc_id = alloc["AllocationId"]
+ assert alloc_id.startswith("eipalloc-")
+ assert "PublicIp" in alloc
+
+ resp = ec2.run_instances(ImageId="ami-00000000", MinCount=1, MaxCount=1)
+ iid = resp["Instances"][0]["InstanceId"]
+
+ assoc = ec2.associate_address(AllocationId=alloc_id, InstanceId=iid)
+ assert "AssociationId" in assoc
+
+ desc = ec2.describe_addresses(AllocationIds=[alloc_id])
+ assert desc["Addresses"][0]["InstanceId"] == iid
+
+ ec2.disassociate_address(AssociationId=assoc["AssociationId"])
+ ec2.release_address(AllocationId=alloc_id)
+ ec2.terminate_instances(InstanceIds=[iid])
+
+
+def test_ec2_tags_crud(ec2):
+ resp = ec2.run_instances(ImageId="ami-00000000", MinCount=1, MaxCount=1)
+ iid = resp["Instances"][0]["InstanceId"]
+
+ ec2.create_tags(Resources=[iid], Tags=[{"Key": "Name", "Value": "qa-box"}])
+
+ desc = ec2.describe_instances(InstanceIds=[iid])
+ tags = desc["Reservations"][0]["Instances"][0]["Tags"]
+ assert any(t["Key"] == "Name" and t["Value"] == "qa-box" for t in tags)
+
+ ec2.delete_tags(Resources=[iid], Tags=[{"Key": "Name"}])
+ desc2 = ec2.describe_instances(InstanceIds=[iid])
+ tags2 = desc2["Reservations"][0]["Instances"][0].get("Tags", [])
+ assert not any(t["Key"] == "Name" for t in tags2)
+
+ ec2.terminate_instances(InstanceIds=[iid])
+
+
+def test_ec2_modify_vpc_attribute(ec2):
+ vpc_id = ec2.create_vpc(CidrBlock="10.10.0.0/16")["Vpc"]["VpcId"]
+ ec2.modify_vpc_attribute(VpcId=vpc_id, EnableDnsSupport={"Value": True})
+ ec2.modify_vpc_attribute(VpcId=vpc_id, EnableDnsHostnames={"Value": True})
+ ec2.delete_vpc(VpcId=vpc_id)
+
+
+def test_ec2_modify_subnet_attribute(ec2):
+ vpc_id = ec2.create_vpc(CidrBlock="10.11.0.0/16")["Vpc"]["VpcId"]
+ subnet_id = ec2.create_subnet(VpcId=vpc_id, CidrBlock="10.11.1.0/24")["Subnet"]["SubnetId"]
+ ec2.modify_subnet_attribute(SubnetId=subnet_id, MapPublicIpOnLaunch={"Value": True})
+ desc = ec2.describe_subnets(SubnetIds=[subnet_id])
+ assert desc["Subnets"][0]["MapPublicIpOnLaunch"] is True
+ ec2.delete_subnet(SubnetId=subnet_id)
+ ec2.delete_vpc(VpcId=vpc_id)
+
+
+def test_ec2_route_table_crud(ec2):
+ vpc_id = ec2.create_vpc(CidrBlock="10.20.0.0/16")["Vpc"]["VpcId"]
+ rtb_id = ec2.create_route_table(VpcId=vpc_id)["RouteTable"]["RouteTableId"]
+ assert rtb_id.startswith("rtb-")
+
+ desc = ec2.describe_route_tables(RouteTableIds=[rtb_id])
+ assert desc["RouteTables"][0]["RouteTableId"] == rtb_id
+
+ ec2.delete_route_table(RouteTableId=rtb_id)
+ ec2.delete_vpc(VpcId=vpc_id)
+
+
+def test_ec2_route_table_associate_disassociate(ec2):
+ vpc_id = ec2.create_vpc(CidrBlock="10.21.0.0/16")["Vpc"]["VpcId"]
+ subnet_id = ec2.create_subnet(VpcId=vpc_id, CidrBlock="10.21.1.0/24")["Subnet"]["SubnetId"]
+ rtb_id = ec2.create_route_table(VpcId=vpc_id)["RouteTable"]["RouteTableId"]
+
+ assoc_id = ec2.associate_route_table(
+ RouteTableId=rtb_id, SubnetId=subnet_id
+ )["AssociationId"]
+ assert assoc_id.startswith("rtbassoc-")
+
+ desc = ec2.describe_route_tables(RouteTableIds=[rtb_id])
+ assocs = desc["RouteTables"][0]["Associations"]
+ assert any(a["RouteTableAssociationId"] == assoc_id for a in assocs)
+
+ ec2.disassociate_route_table(AssociationId=assoc_id)
+ desc2 = ec2.describe_route_tables(RouteTableIds=[rtb_id])
+ assert not any(a["RouteTableAssociationId"] == assoc_id
+ for a in desc2["RouteTables"][0]["Associations"])
+
+ ec2.delete_route_table(RouteTableId=rtb_id)
+ ec2.delete_subnet(SubnetId=subnet_id)
+ ec2.delete_vpc(VpcId=vpc_id)
+
+
+def test_ec2_route_create_replace_delete(ec2):
+ vpc_id = ec2.create_vpc(CidrBlock="10.22.0.0/16")["Vpc"]["VpcId"]
+ rtb_id = ec2.create_route_table(VpcId=vpc_id)["RouteTable"]["RouteTableId"]
+ igw_id = ec2.create_internet_gateway()["InternetGateway"]["InternetGatewayId"]
+
+ ec2.create_route(RouteTableId=rtb_id, DestinationCidrBlock="0.0.0.0/0",
+ GatewayId=igw_id)
+ desc = ec2.describe_route_tables(RouteTableIds=[rtb_id])
+ routes = desc["RouteTables"][0]["Routes"]
+ assert any(r.get("DestinationCidrBlock") == "0.0.0.0/0" for r in routes)
+
+ ec2.replace_route(RouteTableId=rtb_id, DestinationCidrBlock="0.0.0.0/0",
+ GatewayId="local")
+
+ ec2.delete_route(RouteTableId=rtb_id, DestinationCidrBlock="0.0.0.0/0")
+ desc2 = ec2.describe_route_tables(RouteTableIds=[rtb_id])
+ assert not any(r.get("DestinationCidrBlock") == "0.0.0.0/0"
+ for r in desc2["RouteTables"][0]["Routes"])
+
+ ec2.delete_internet_gateway(InternetGatewayId=igw_id)
+ ec2.delete_route_table(RouteTableId=rtb_id)
+ ec2.delete_vpc(VpcId=vpc_id)
+
+
+def test_ec2_network_interface_crud(ec2):
+ vpc_id = ec2.create_vpc(CidrBlock="10.30.0.0/16")["Vpc"]["VpcId"]
+ subnet_id = ec2.create_subnet(VpcId=vpc_id, CidrBlock="10.30.1.0/24")["Subnet"]["SubnetId"]
+
+ eni_id = ec2.create_network_interface(
+ SubnetId=subnet_id, Description="qa-eni"
+ )["NetworkInterface"]["NetworkInterfaceId"]
+ assert eni_id.startswith("eni-")
+
+ desc = ec2.describe_network_interfaces(NetworkInterfaceIds=[eni_id])
+ assert desc["NetworkInterfaces"][0]["Description"] == "qa-eni"
+ assert desc["NetworkInterfaces"][0]["Status"] == "available"
+
+ ec2.delete_network_interface(NetworkInterfaceId=eni_id)
+ desc2 = ec2.describe_network_interfaces()
+ assert not any(e["NetworkInterfaceId"] == eni_id for e in desc2["NetworkInterfaces"])
+
+ ec2.delete_subnet(SubnetId=subnet_id)
+ ec2.delete_vpc(VpcId=vpc_id)
+
+
+def test_ec2_network_interface_attach_detach(ec2):
+ vpc_id = ec2.create_vpc(CidrBlock="10.31.0.0/16")["Vpc"]["VpcId"]
+ subnet_id = ec2.create_subnet(VpcId=vpc_id, CidrBlock="10.31.1.0/24")["Subnet"]["SubnetId"]
+ eni_id = ec2.create_network_interface(SubnetId=subnet_id)["NetworkInterface"]["NetworkInterfaceId"]
+ resp = ec2.run_instances(ImageId="ami-00000000", MinCount=1, MaxCount=1)
+ iid = resp["Instances"][0]["InstanceId"]
+
+ attach_resp = ec2.attach_network_interface(
+ NetworkInterfaceId=eni_id, InstanceId=iid, DeviceIndex=1
+ )
+ attachment_id = attach_resp["AttachmentId"]
+ assert attachment_id.startswith("eni-attach-")
+
+ desc = ec2.describe_network_interfaces(NetworkInterfaceIds=[eni_id])
+ assert desc["NetworkInterfaces"][0]["Status"] == "in-use"
+
+ ec2.detach_network_interface(AttachmentId=attachment_id)
+ desc2 = ec2.describe_network_interfaces(NetworkInterfaceIds=[eni_id])
+ assert desc2["NetworkInterfaces"][0]["Status"] == "available"
+
+ ec2.terminate_instances(InstanceIds=[iid])
+ ec2.delete_network_interface(NetworkInterfaceId=eni_id)
+ ec2.delete_subnet(SubnetId=subnet_id)
+ ec2.delete_vpc(VpcId=vpc_id)
+
+
+def test_ec2_vpc_endpoint_crud(ec2):
+ vpc_id = ec2.create_vpc(CidrBlock="10.40.0.0/16")["Vpc"]["VpcId"]
+
+ vpce_id = ec2.create_vpc_endpoint(
+ VpcId=vpc_id,
+ ServiceName="com.amazonaws.us-east-1.s3",
+ VpcEndpointType="Gateway",
+ )["VpcEndpoint"]["VpcEndpointId"]
+ assert vpce_id.startswith("vpce-")
+
+ desc = ec2.describe_vpc_endpoints(VpcEndpointIds=[vpce_id])
+ assert desc["VpcEndpoints"][0]["ServiceName"] == "com.amazonaws.us-east-1.s3"
+ assert desc["VpcEndpoints"][0]["State"] == "available"
+
+ ec2.delete_vpc_endpoints(VpcEndpointIds=[vpce_id])
+ desc2 = ec2.describe_vpc_endpoints()
+ assert not any(e["VpcEndpointId"] == vpce_id for e in desc2["VpcEndpoints"])
+
+ ec2.delete_vpc(VpcId=vpc_id)
+
+
+def test_ec2_describe_route_tables_default(ec2):
+ desc = ec2.describe_route_tables()
+ assert any(rt["VpcId"] == "vpc-00000001" for rt in desc["RouteTables"])