Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
feat: EBS volumes/snapshots + EFS file systems — 671 tests (v1.1.3) (#32)
Nahuel Nucera0ae80693926c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6abd58f8..7604db81 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,42 @@ Versioning follows [Semantic Versioning](https://semver.org/).---+## [1.1.3] — 2026-03-30++### Added+- **Amazon EBS** (Elastic Block Store) — added to the EC2 Query/XML service handler+ - **Volumes**: `CreateVolume`, `DeleteVolume`, `DescribeVolumes`, `DescribeVolumeStatus`,+ `AttachVolume`, `DetachVolume`, `ModifyVolume`, `DescribeVolumesModifications`,+ `EnableVolumeIO`, `ModifyVolumeAttribute`, `DescribeVolumeAttribute`+ - **Snapshots**: `CreateSnapshot`, `DeleteSnapshot`, `DescribeSnapshots`,+ `CopySnapshot`, `ModifySnapshotAttribute`, `DescribeSnapshotAttribute`+ - All three volume types supported (gp2/gp3/io1/io2/st1/sc1)+ - Attach/Detach updates volume state (available ↔ in-use)+ - ModifyVolume returns `completed` immediately+ - Snapshots store as `completed` (emulator — no real EBS)+ - Pro-only on LocalStack — free here+ - 8 integration tests++- **Amazon EFS** (Elastic File System) — new service (`ministack/services/efs.py`)+ - REST/JSON protocol via `/2015-02-01/*` paths, credential scope `elasticfilesystem`+ - **File Systems**: `CreateFileSystem`, `DescribeFileSystems`, `DeleteFileSystem`,+ `UpdateFileSystem` — CreationToken idempotency enforced+ - **Mount Targets**: `CreateMountTarget`, `DescribeMountTargets`, `DeleteMountTarget`,+ `DescribeMountTargetSecurityGroups`, `ModifyMountTargetSecurityGroups`+ - **Access Points**: `CreateAccessPoint`, `DescribeAccessPoints`, `DeleteAccessPoint`+ - **Tags**: `TagResource`, `UntagResource`, `ListTagsForResource`+ - **Lifecycle**: `PutLifecycleConfiguration`, `DescribeLifecycleConfiguration`+ - **Backup Policy**: `PutBackupPolicy`, `DescribeBackupPolicy`+ - **Account**: `DescribeAccountPreferences`, `PutAccountPreferences`+ - FileSystem with active mount targets blocks deletion (`FileSystemInUse`)+ - Pro-only on LocalStack — free here+ - 10 integration tests++### Tests+- 671 integration tests — all passing (672 - 1 flaky Docker ECS test)++---+## [1.1.2] — 2026-03-29### Addeddiff --git a/README.md b/README.mdindex 7d696d3d..d549d982 100644--- a/README.md+++ b/README.md@@ -236,6 +236,8 @@ subnet = ec2.create_subnet(| **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) |+| **EBS** | CreateVolume, DeleteVolume, DescribeVolumes, DescribeVolumeStatus, AttachVolume, DetachVolume, ModifyVolume, DescribeVolumesModifications, EnableVolumeIO, ModifyVolumeAttribute, DescribeVolumeAttribute, CreateSnapshot, DeleteSnapshot, DescribeSnapshots, CopySnapshot, ModifySnapshotAttribute, DescribeSnapshotAttribute | Part of EC2 Query/XML service; attach/detach updates volume state; snapshots stored as completed immediately; Pro-only on LocalStack — free here |+| **EFS** | CreateFileSystem, DescribeFileSystems, DeleteFileSystem, UpdateFileSystem, CreateMountTarget, DescribeMountTargets, DeleteMountTarget, DescribeMountTargetSecurityGroups, ModifyMountTargetSecurityGroups, CreateAccessPoint, DescribeAccessPoints, DeleteAccessPoint, TagResource, UntagResource, ListTagsForResource, PutLifecycleConfiguration, DescribeLifecycleConfiguration, PutBackupPolicy, DescribeBackupPolicy, DescribeAccountPreferences, PutAccountPreferences | REST/JSON `/2015-02-01/*`; CreationToken idempotency; FileSystem deletion blocked when mount targets exist; Pro-only on LocalStack — free here || **EMR** | RunJobFlow, DescribeCluster, ListClusters, TerminateJobFlows, ModifyCluster, SetTerminationProtection, SetVisibleToAllUsers, AddJobFlowSteps, DescribeStep, ListSteps, CancelSteps, AddInstanceFleet, ListInstanceFleets, ModifyInstanceFleet, AddInstanceGroups, ListInstanceGroups, ModifyInstanceGroups, ListBootstrapActions, AddTags, RemoveTags, GetBlockPublicAccessConfiguration, PutBlockPublicAccessConfiguration | Control plane only — no real Spark/Hadoop; clusters start in WAITING (KeepAlive=true) or TERMINATED (KeepAlive=false); steps stored as COMPLETED immediately; all three instance modes (simple, InstanceGroups, InstanceFleets); TerminationProtected enforced; Pro-only on LocalStack — free here || **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 |@@ -508,6 +510,7 @@ provider "aws" {cognitoidentity = "http://localhost:4566"ec2 = "http://localhost:4566"emr = "http://localhost:4566"+ efs = "http://localhost:4566"}}```@@ -559,6 +562,8 @@ config:| **Cognito** | ✅ | ✅ | ✅ || **EC2** | ✅ | ✅ | ✅ || **EMR** | ✅ | Paid | ✅ |+| **EBS** | ✅ | Paid | ✅ |+| **EFS** | ✅ | Paid | ✅ || 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.pyindex bb6febf6..202fe22f 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -32,6 +32,7 @@ from ministack.services import apigateway_v1from ministack.services import route53from ministack.services import cognitofrom ministack.services import emr+from ministack.services import efsfrom ministack.services.iam_sts import handle_iam_request, handle_sts_requestLOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO").upper()@@ -70,6 +71,7 @@ SERVICE_HANDLERS = {"cognito-identity": cognito.handle_request,"ec2": ec2.handle_request,"elasticmapreduce": emr.handle_request,+ "elasticfilesystem": efs.handle_request,}SERVICE_NAME_ALIASES = {@@ -120,7 +122,7 @@ BANNER = r"""Services: S3, SQS, SNS, DynamoDB, Lambda, IAM, STS, SecretsManager, CloudWatch Logs,SSM, EventBridge, Kinesis, CloudWatch, SES, Step Functions,ECS, RDS, ElastiCache, Glue, Athena, API Gateway, Firehose, Route53,- Cognito, EC2, EMR+ Cognito, EC2, EMR, EFS"""@@ -378,6 +380,7 @@ def _reset_all_state():(cognito, cognito.reset),(ec2, ec2.reset),(emr, emr.reset),+ (efs, efs.reset),]:try:fn()diff --git a/ministack/core/router.py b/ministack/core/router.pyindex b8377a80..b41297ff 100644--- a/ministack/core/router.py+++ b/ministack/core/router.py@@ -120,6 +120,11 @@ SERVICE_PATTERNS = {"target_prefixes": ["ElasticMapReduce"],"host_patterns": [r"elasticmapreduce\."],},+ "elasticfilesystem": {+ "host_patterns": [r"elasticfilesystem\."],+ "path_prefixes": ["/2015-02-01/"],+ "credential_scope": "elasticfilesystem",+ },"ec2": {"host_patterns": [r"ec2\."],"path_patterns": [r"Action=.*Instance", r"Action=.*Security", r"Action=.*KeyPair",@@ -170,6 +175,7 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->"cognito-idp": "cognito-idp","cognito-identity": "cognito-identity","elasticmapreduce": "elasticmapreduce",+ "elasticfilesystem": "elasticfilesystem",}if svc_name in scope_map:return scope_map[svc_name]@@ -305,6 +311,16 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->"AttachNetworkInterface": "ec2", "DetachNetworkInterface": "ec2","CreateVpcEndpoint": "ec2", "DeleteVpcEndpoints": "ec2","DescribeVpcEndpoints": "ec2",+ # EBS Volumes+ "CreateVolume": "ec2", "DeleteVolume": "ec2", "DescribeVolumes": "ec2",+ "DescribeVolumeStatus": "ec2", "AttachVolume": "ec2", "DetachVolume": "ec2",+ "ModifyVolume": "ec2", "DescribeVolumesModifications": "ec2",+ "EnableVolumeIO": "ec2", "ModifyVolumeAttribute": "ec2",+ "DescribeVolumeAttribute": "ec2",+ # EBS Snapshots+ "CreateSnapshot": "ec2", "DeleteSnapshot": "ec2", "DescribeSnapshots": "ec2",+ "CopySnapshot": "ec2", "ModifySnapshotAttribute": "ec2",+ "DescribeSnapshotAttribute": "ec2",}if action in action_service_map:return action_service_map[action]diff --git a/ministack/services/ec2.py b/ministack/services/ec2.pyindex 2adb219d..fa541d95 100644--- a/ministack/services/ec2.py+++ b/ministack/services/ec2.py@@ -24,6 +24,11 @@ Supports:ENI: CreateNetworkInterface, DeleteNetworkInterface, DescribeNetworkInterfaces,AttachNetworkInterface, DetachNetworkInterfaceVPC Endpoints: CreateVpcEndpoint, DeleteVpcEndpoints, DescribeVpcEndpoints+ EBS Volumes: CreateVolume, DeleteVolume, DescribeVolumes, DescribeVolumeStatus,+ AttachVolume, DetachVolume, ModifyVolume, DescribeVolumesModifications,+ EnableVolumeIO, ModifyVolumeAttribute, DescribeVolumeAttribute+ EBS Snapshots: CreateSnapshot, DeleteSnapshot, DescribeSnapshots,+ ModifySnapshotAttribute, DescribeSnapshotAttribute, CopySnapshot"""import os@@ -55,6 +60,8 @@ _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+_volumes: dict = {} # vol_id -> volume record+_snapshots: dict = {} # snap_id -> snapshot record# Default VPC / subnet created at import time so DescribeVpcs always returns something_DEFAULT_VPC_ID = "vpc-00000001"@@ -1009,6 +1016,302 @@ def _describe_tags(p):return _xml(200, "DescribeTagsResponse", f"<tagSet>{items}</tagSet>")+# ---------------------------------------------------------------------------+# EBS Volumes+# ---------------------------------------------------------------------------++def _new_volume_id():+ return "vol-" + "".join(random.choices(string.hexdigits[:16], k=17))++def _new_snapshot_id():+ return "snap-" + "".join(random.choices(string.hexdigits[:16], k=17))+++def _create_volume(p):+ vol_id = _new_volume_id()+ az = _p(p, "AvailabilityZone") or f"{REGION}a"+ size = int(_p(p, "Size") or "8")+ vol_type = _p(p, "VolumeType") or "gp2"+ snapshot_id = _p(p, "SnapshotId") or ""+ iops = _p(p, "Iops") or ""+ encrypted = _p(p, "Encrypted") or "false"+ now = _now_ts()+ _volumes[vol_id] = {+ "VolumeId": vol_id,+ "Size": size,+ "AvailabilityZone": az,+ "State": "available",+ "VolumeType": vol_type,+ "SnapshotId": snapshot_id,+ "Iops": int(iops) if iops else (3000 if vol_type in ("gp3", "io1", "io2") else 0),+ "Encrypted": encrypted.lower() == "true",+ "CreateTime": now,+ "Attachments": [],+ "MultiAttachEnabled": False,+ "Throughput": 125 if vol_type == "gp3" else 0,+ }+ return _xml(200, "CreateVolumeResponse", _volume_inner_xml(_volumes[vol_id]))+++def _delete_volume(p):+ vol_id = _p(p, "VolumeId")+ if vol_id not in _volumes:+ return _error("InvalidVolume.NotFound", f"The volume '{vol_id}' does not exist.", 400)+ vol = _volumes[vol_id]+ if vol["Attachments"]:+ return _error("VolumeInUse", f"Volume {vol_id} is currently attached.", 400)+ del _volumes[vol_id]+ return _xml(200, "DeleteVolumeResponse", "<return>true</return>")+++def _describe_volumes(p):+ filter_ids = _parse_member_list(p, "VolumeId")+ items = ""+ for vol in _volumes.values():+ if filter_ids and vol["VolumeId"] not in filter_ids:+ continue+ items += f"<item>{_volume_inner_xml(vol)}</item>"+ return _xml(200, "DescribeVolumesResponse", f"<volumeSet>{items}</volumeSet>")+++def _describe_volume_status(p):+ filter_ids = _parse_member_list(p, "VolumeId")+ items = ""+ for vol in _volumes.values():+ if filter_ids and vol["VolumeId"] not in filter_ids:+ continue+ items += f"""<item>+ <volumeId>{vol['VolumeId']}</volumeId>+ <availabilityZone>{vol['AvailabilityZone']}</availabilityZone>+ <volumeStatus>+ <status>ok</status>+ <details><item><name>io-enabled</name><status>passed</status></item></details>+ </volumeStatus>+ <actionsSet/>+ <eventsSet/>+ </item>"""+ return _xml(200, "DescribeVolumeStatusResponse", f"<volumeStatusSet>{items}</volumeStatusSet>")+++def _attach_volume(p):+ vol_id = _p(p, "VolumeId")+ instance_id = _p(p, "InstanceId")+ device = _p(p, "Device") or "/dev/xvdf"+ vol = _volumes.get(vol_id)+ if not vol:+ return _error("InvalidVolume.NotFound", f"The volume '{vol_id}' does not exist.", 400)+ if not _instances.get(instance_id):+ return _error("InvalidInstanceID.NotFound", f"The instance ID '{instance_id}' does not exist.", 400)+ now = _now_ts()+ attachment = {+ "VolumeId": vol_id,+ "InstanceId": instance_id,+ "Device": device,+ "State": "attached",+ "AttachTime": now,+ "DeleteOnTermination": False,+ }+ vol["Attachments"] = [attachment]+ vol["State"] = "in-use"+ return _xml(200, "AttachVolumeResponse", f"""+ <volumeId>{vol_id}</volumeId>+ <instanceId>{instance_id}</instanceId>+ <device>{device}</device>+ <status>attached</status>+ <attachTime>{now}</attachTime>+ <deleteOnTermination>false</deleteOnTermination>""")+++def _detach_volume(p):+ vol_id = _p(p, "VolumeId")+ vol = _volumes.get(vol_id)+ if not vol:+ return _error("InvalidVolume.NotFound", f"The volume '{vol_id}' does not exist.", 400)+ vol["Attachments"] = []+ vol["State"] = "available"+ return _xml(200, "DetachVolumeResponse", f"""+ <volumeId>{vol_id}</volumeId>+ <status>detached</status>""")+++def _modify_volume(p):+ vol_id = _p(p, "VolumeId")+ vol = _volumes.get(vol_id)+ if not vol:+ return _error("InvalidVolume.NotFound", f"The volume '{vol_id}' does not exist.", 400)+ if _p(p, "Size"):+ vol["Size"] = int(_p(p, "Size"))+ if _p(p, "VolumeType"):+ vol["VolumeType"] = _p(p, "VolumeType")+ if _p(p, "Iops"):+ vol["Iops"] = int(_p(p, "Iops"))+ now = _now_ts()+ return _xml(200, "ModifyVolumeResponse", f"""+ <volumeModification>+ <volumeId>{vol_id}</volumeId>+ <modificationState>completed</modificationState>+ <targetSize>{vol['Size']}</targetSize>+ <targetVolumeType>{vol['VolumeType']}</targetVolumeType>+ <targetIops>{vol['Iops']}</targetIops>+ <startTime>{now}</startTime>+ <endTime>{now}</endTime>+ <progress>100</progress>+ </volumeModification>""")+++def _describe_volumes_modifications(p):+ filter_ids = _parse_member_list(p, "VolumeId")+ items = ""+ for vol in _volumes.values():+ if filter_ids and vol["VolumeId"] not in filter_ids:+ continue+ now = _now_ts()+ items += f"""<item>+ <volumeId>{vol['VolumeId']}</volumeId>+ <modificationState>completed</modificationState>+ <targetSize>{vol['Size']}</targetSize>+ <targetVolumeType>{vol['VolumeType']}</targetVolumeType>+ <targetIops>{vol['Iops']}</targetIops>+ <startTime>{now}</startTime>+ <endTime>{now}</endTime>+ <progress>100</progress>+ </item>"""+ return _xml(200, "DescribeVolumesModificationsResponse", f"<volumeModificationSet>{items}</volumeModificationSet>")+++def _enable_volume_io(p):+ return _xml(200, "EnableVolumeIOResponse", "<return>true</return>")+++def _modify_volume_attribute(p):+ return _xml(200, "ModifyVolumeAttributeResponse", "<return>true</return>")+++def _describe_volume_attribute(p):+ vol_id = _p(p, "VolumeId")+ attribute = _p(p, "Attribute") or "autoEnableIO"+ return _xml(200, "DescribeVolumeAttributeResponse", f"""+ <volumeId>{vol_id}</volumeId>+ <autoEnableIO><value>false</value></autoEnableIO>""")+++def _volume_inner_xml(vol):+ attachments = "".join(f"""<item>+ <volumeId>{a['VolumeId']}</volumeId>+ <instanceId>{a['InstanceId']}</instanceId>+ <device>{a['Device']}</device>+ <status>{a['State']}</status>+ <attachTime>{a['AttachTime']}</attachTime>+ <deleteOnTermination>{'true' if a['DeleteOnTermination'] else 'false'}</deleteOnTermination>+ </item>""" for a in vol.get("Attachments", []))+ snap = f"<snapshotId>{vol['SnapshotId']}</snapshotId>" if vol.get("SnapshotId") else "<snapshotId/>"+ iops = f"<iops>{vol['Iops']}</iops>" if vol.get("Iops") else ""+ return f"""+ <volumeId>{vol['VolumeId']}</volumeId>+ <size>{vol['Size']}</size>+ <availabilityZone>{vol['AvailabilityZone']}</availabilityZone>+ <status>{vol['State']}</status>+ <createTime>{vol['CreateTime']}</createTime>+ <volumeType>{vol['VolumeType']}</volumeType>+ {snap}+ {iops}+ <encrypted>{'true' if vol['Encrypted'] else 'false'}</encrypted>+ <multiAttachEnabled>{'true' if vol['MultiAttachEnabled'] else 'false'}</multiAttachEnabled>+ <attachmentSet>{attachments}</attachmentSet>+ <tagSet/>"""+++# ---------------------------------------------------------------------------+# EBS Snapshots+# ---------------------------------------------------------------------------++def _create_snapshot(p):+ vol_id = _p(p, "VolumeId")+ description = _p(p, "Description") or ""+ vol = _volumes.get(vol_id)+ if not vol:+ return _error("InvalidVolume.NotFound", f"The volume '{vol_id}' does not exist.", 400)+ snap_id = _new_snapshot_id()+ now = _now_ts()+ _snapshots[snap_id] = {+ "SnapshotId": snap_id,+ "VolumeId": vol_id,+ "VolumeSize": vol["Size"],+ "Description": description,+ "State": "completed",+ "StartTime": now,+ "Progress": "100%",+ "OwnerId": ACCOUNT_ID,+ "Encrypted": vol["Encrypted"],+ "StorageTier": "standard",+ }+ return _xml(200, "CreateSnapshotResponse", _snapshot_inner_xml(_snapshots[snap_id]))+++def _delete_snapshot(p):+ snap_id = _p(p, "SnapshotId")+ if snap_id not in _snapshots:+ return _error("InvalidSnapshot.NotFound", f"The snapshot '{snap_id}' does not exist.", 400)+ del _snapshots[snap_id]+ return _xml(200, "DeleteSnapshotResponse", "<return>true</return>")+++def _describe_snapshots(p):+ filter_ids = _parse_member_list(p, "SnapshotId")+ owner_ids = _parse_member_list(p, "Owner")+ items = ""+ for snap in _snapshots.values():+ if filter_ids and snap["SnapshotId"] not in filter_ids:+ continue+ if owner_ids and snap["OwnerId"] not in owner_ids and "self" not in owner_ids:+ continue+ items += f"<item>{_snapshot_inner_xml(snap)}</item>"+ return _xml(200, "DescribeSnapshotsResponse", f"<snapshotSet>{items}</snapshotSet>")+++def _copy_snapshot(p):+ source_snap_id = _p(p, "SourceSnapshotId")+ description = _p(p, "Description") or ""+ source = _snapshots.get(source_snap_id)+ if not source:+ return _error("InvalidSnapshot.NotFound", f"The snapshot '{source_snap_id}' does not exist.", 400)+ new_snap_id = _new_snapshot_id()+ now = _now_ts()+ _snapshots[new_snap_id] = {+ **source,+ "SnapshotId": new_snap_id,+ "Description": description or source["Description"],+ "StartTime": now,+ }+ return _xml(200, "CopySnapshotResponse", f"<snapshotId>{new_snap_id}</snapshotId>")+++def _modify_snapshot_attribute(p):+ return _xml(200, "ModifySnapshotAttributeResponse", "<return>true</return>")+++def _describe_snapshot_attribute(p):+ snap_id = _p(p, "SnapshotId")+ return _xml(200, "DescribeSnapshotAttributeResponse", f"""+ <snapshotId>{snap_id}</snapshotId>+ <createVolumePermission/>""")+++def _snapshot_inner_xml(snap):+ return f"""+ <snapshotId>{snap['SnapshotId']}</snapshotId>+ <volumeId>{snap['VolumeId']}</volumeId>+ <status>{snap['State']}</status>+ <startTime>{snap['StartTime']}</startTime>+ <progress>{snap['Progress']}</progress>+ <ownerId>{snap['OwnerId']}</ownerId>+ <volumeSize>{snap['VolumeSize']}</volumeSize>+ <description>{snap['Description']}</description>+ <encrypted>{'true' if snap['Encrypted'] else 'false'}</encrypted>+ <storageTier>{snap['StorageTier']}</storageTier>+ <tagSet/>"""++# ---------------------------------------------------------------------------# XML helpers# ---------------------------------------------------------------------------@@ -1364,6 +1667,10 @@ def _guess_resource_type(resource_id):return "network-interface"if resource_id.startswith("vpce-"):return "vpc-endpoint"+ if resource_id.startswith("vol-"):+ return "volume"+ if resource_id.startswith("snap-"):+ return "snapshot"return "resource"@@ -1410,6 +1717,8 @@ def reset():_route_tables.clear()_network_interfaces.clear()_vpc_endpoints.clear()+ _volumes.clear()+ _snapshots.clear()_init_defaults()@@ -1474,4 +1783,23 @@ _ACTION_MAP = {"CreateVpcEndpoint": _create_vpc_endpoint,"DeleteVpcEndpoints": _delete_vpc_endpoints,"DescribeVpcEndpoints": _describe_vpc_endpoints,+ # EBS Volumes+ "CreateVolume": _create_volume,+ "DeleteVolume": _delete_volume,+ "DescribeVolumes": _describe_volumes,+ "DescribeVolumeStatus": _describe_volume_status,+ "AttachVolume": _attach_volume,+ "DetachVolume": _detach_volume,+ "ModifyVolume": _modify_volume,+ "DescribeVolumesModifications": _describe_volumes_modifications,+ "EnableVolumeIO": _enable_volume_io,+ "ModifyVolumeAttribute": _modify_volume_attribute,+ "DescribeVolumeAttribute": _describe_volume_attribute,+ # EBS Snapshots+ "CreateSnapshot": _create_snapshot,+ "DeleteSnapshot": _delete_snapshot,+ "DescribeSnapshots": _describe_snapshots,+ "CopySnapshot": _copy_snapshot,+ "ModifySnapshotAttribute": _modify_snapshot_attribute,+ "DescribeSnapshotAttribute": _describe_snapshot_attribute,}diff --git a/ministack/services/efs.py b/ministack/services/efs.pynew file mode 100644index 00000000..f855d52f--- /dev/null+++ b/ministack/services/efs.py@@ -0,0 +1,509 @@+"""+EFS (Elastic File System) Service Emulator.+REST/JSON protocol — /2015-02-01/* paths.+In-memory only — no real filesystem.++Supports:+ File Systems: CreateFileSystem, DescribeFileSystems, DeleteFileSystem, UpdateFileSystem+ Mount Targets: CreateMountTarget, DescribeMountTargets, DeleteMountTarget+ DescribeMountTargetSecurityGroups, ModifyMountTargetSecurityGroups+ Access Points: CreateAccessPoint, DescribeAccessPoints, DeleteAccessPoint+ Tags: TagResource, UntagResource, ListTagsForResource,+ CreateTags (legacy), DeleteTags (legacy), DescribeTags (legacy)+ Lifecycle: PutLifecycleConfiguration, DescribeLifecycleConfiguration+ Backup Policy: PutBackupPolicy, DescribeBackupPolicy+ Account: DescribeAccountPreferences, PutAccountPreferences+"""++import os+import json+import random+import string+import logging+import time+import re++logger = logging.getLogger("efs")++ACCOUNT_ID = os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")+REGION = os.environ.get("MINISTACK_REGION", "us-east-1")++# ---------------------------------------------------------------------------+# State+# ---------------------------------------------------------------------------++_file_systems: dict = {} # fs_id -> fs record+_mount_targets: dict = {} # mt_id -> mount target record+_access_points: dict = {} # ap_id -> access point record++# ---------------------------------------------------------------------------+# ID generators+# ---------------------------------------------------------------------------++def _fs_id():+ return "fs-" + "".join(random.choices(string.hexdigits[:16], k=17))++def _mt_id():+ return "fsmt-" + "".join(random.choices(string.hexdigits[:16], k=17))++def _ap_id():+ return "fsap-" + "".join(random.choices(string.hexdigits[:16], k=17))++def _now_iso():+ return time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime())++# ---------------------------------------------------------------------------+# File Systems+# ---------------------------------------------------------------------------++def _create_file_system(body):+ perf_mode = body.get("PerformanceMode", "generalPurpose")+ throughput_mode = body.get("ThroughputMode", "bursting")+ encrypted = body.get("Encrypted", False)+ kms_key_id = body.get("KmsKeyId", "")+ tags = body.get("Tags", [])+ provisioned_throughput = body.get("ProvisionedThroughputInMibps")+ creation_token = body.get("CreationToken", _fs_id())++ # Idempotency — same CreationToken returns existing FS+ for fs in _file_systems.values():+ if fs.get("CreationToken") == creation_token:+ return _json(200, _fs_response(fs))++ fs_id = _fs_id()+ arn = f"arn:aws:elasticfilesystem:{REGION}:{ACCOUNT_ID}:file-system/{fs_id}"+ now = _now_iso()++ record = {+ "FileSystemId": fs_id,+ "FileSystemArn": arn,+ "CreationToken": creation_token,+ "CreationTime": now,+ "LifeCycleState": "available",+ "NumberOfMountTargets": 0,+ "SizeInBytes": {"Value": 0, "Timestamp": now, "ValueInIA": 0, "ValueInStandard": 0},+ "PerformanceMode": perf_mode,+ "ThroughputMode": throughput_mode,+ "Encrypted": encrypted,+ "KmsKeyId": kms_key_id,+ "Tags": tags,+ "OwnerId": ACCOUNT_ID,+ "Name": next((t["Value"] for t in tags if t["Key"] == "Name"), ""),+ }+ if provisioned_throughput:+ record["ProvisionedThroughputInMibps"] = provisioned_throughput++ _file_systems[fs_id] = record+ return _json(201, _fs_response(record))+++def _describe_file_systems(query):+ fs_id = query.get("FileSystemId")+ creation_token = query.get("CreationToken")+ max_items = int(query.get("MaxItems", 100))++ results = []+ for fs in _file_systems.values():+ if fs_id and fs["FileSystemId"] != fs_id:+ continue+ if creation_token and fs.get("CreationToken") != creation_token:+ continue+ results.append(_fs_response(fs))++ return _json(200, {"FileSystems": results[:max_items]})+++def _delete_file_system(fs_id):+ fs = _file_systems.get(fs_id)+ if not fs:+ return _error(404, "FileSystemNotFound", f"File system '{fs_id}' does not exist.")+ if fs["NumberOfMountTargets"] > 0:+ return _error(400, "FileSystemInUse",+ f"File system '{fs_id}' has mount targets and cannot be deleted.")+ del _file_systems[fs_id]+ return _json(204, {})+++def _update_file_system(fs_id, body):+ fs = _file_systems.get(fs_id)+ if not fs:+ return _error(404, "FileSystemNotFound", f"File system '{fs_id}' does not exist.")+ if "ThroughputMode" in body:+ fs["ThroughputMode"] = body["ThroughputMode"]+ if "ProvisionedThroughputInMibps" in body:+ fs["ProvisionedThroughputInMibps"] = body["ProvisionedThroughputInMibps"]+ return _json(202, _fs_response(fs))+++def _fs_response(fs):+ r = {k: v for k, v in fs.items()}+ return r+++# ---------------------------------------------------------------------------+# Mount Targets+# ---------------------------------------------------------------------------++def _create_mount_target(body):+ fs_id = body.get("FileSystemId")+ subnet_id = body.get("SubnetId", "")+ ip_address = body.get("IpAddress", f"10.0.{random.randint(0,255)}.{random.randint(1,254)}")+ security_groups = body.get("SecurityGroups", [])++ fs = _file_systems.get(fs_id)+ if not fs:+ return _error(404, "FileSystemNotFound", f"File system '{fs_id}' does not exist.")++ mt_id = _mt_id()+ arn = f"arn:aws:elasticfilesystem:{REGION}:{ACCOUNT_ID}:file-system/{fs_id}/mount-target/{mt_id}"+ now = _now_iso()++ record = {+ "MountTargetId": mt_id,+ "FileSystemId": fs_id,+ "SubnetId": subnet_id,+ "AvailabilityZoneId": f"use1-az{random.randint(1,3)}",+ "AvailabilityZoneName": f"{REGION}a",+ "VpcId": "vpc-00000001",+ "LifeCycleState": "available",+ "IpAddress": ip_address,+ "NetworkInterfaceId": f"eni-{random.choices(string.hexdigits[:16], k=17)}",+ "OwnerId": ACCOUNT_ID,+ "MountTargetArn": arn,+ "SecurityGroups": security_groups,+ }+ _mount_targets[mt_id] = record+ fs["NumberOfMountTargets"] = fs.get("NumberOfMountTargets", 0) + 1++ return _json(200, _mt_response(record))+++def _describe_mount_targets(query):+ fs_id = query.get("FileSystemId")+ mt_id = query.get("MountTargetId")+ max_items = int(query.get("MaxItems", 100))++ results = []+ for mt in _mount_targets.values():+ if fs_id and mt["FileSystemId"] != fs_id:+ continue+ if mt_id and mt["MountTargetId"] != mt_id:+ continue+ results.append(_mt_response(mt))++ return _json(200, {"MountTargets": results[:max_items]})+++def _delete_mount_target(mt_id):+ mt = _mount_targets.get(mt_id)+ if not mt:+ return _error(404, "MountTargetNotFound", f"Mount target '{mt_id}' does not exist.")+ fs = _file_systems.get(mt["FileSystemId"])+ if fs:+ fs["NumberOfMountTargets"] = max(0, fs.get("NumberOfMountTargets", 1) - 1)+ del _mount_targets[mt_id]+ return _json(204, {})+++def _describe_mount_target_security_groups(mt_id):+ mt = _mount_targets.get(mt_id)+ if not mt:+ return _error(404, "MountTargetNotFound", f"Mount target '{mt_id}' does not exist.")+ return _json(200, {"SecurityGroups": mt.get("SecurityGroups", [])})+++def _modify_mount_target_security_groups(mt_id, body):+ mt = _mount_targets.get(mt_id)+ if not mt:+ return _error(404, "MountTargetNotFound", f"Mount target '{mt_id}' does not exist.")+ mt["SecurityGroups"] = body.get("SecurityGroups", [])+ return _json(204, {})+++def _mt_response(mt):+ return {k: v for k, v in mt.items() if k != "SecurityGroups"}+++# ---------------------------------------------------------------------------+# Access Points+# ---------------------------------------------------------------------------++def _create_access_point(body):+ fs_id = body.get("FileSystemId")+ fs = _file_systems.get(fs_id)+ if not fs:+ return _error(404, "FileSystemNotFound", f"File system '{fs_id}' does not exist.")++ ap_id = _ap_id()+ arn = f"arn:aws:elasticfilesystem:{REGION}:{ACCOUNT_ID}:access-point/{ap_id}"+ now = _now_iso()+ tags = body.get("Tags", [])++ record = {+ "AccessPointId": ap_id,+ "AccessPointArn": arn,+ "FileSystemId": fs_id,+ "LifeCycleState": "available",+ "ClientToken": body.get("ClientToken", ap_id),+ "PosixUser": body.get("PosixUser", {}),+ "RootDirectory": body.get("RootDirectory", {"Path": "/"}),+ "Tags": tags,+ "OwnerId": ACCOUNT_ID,+ "Name": next((t["Value"] for t in tags if t["Key"] == "Name"), ""),+ }+ _access_points[ap_id] = record+ return _json(200, record)+++def _describe_access_points(query):+ fs_id = query.get("FileSystemId")+ ap_id = query.get("AccessPointId")+ max_results = int(query.get("MaxResults", 100))++ results = []+ for ap in _access_points.values():+ if fs_id and ap["FileSystemId"] != fs_id:+ continue+ if ap_id and ap["AccessPointId"] != ap_id:+ continue+ results.append(ap)++ return _json(200, {"AccessPoints": results[:max_results]})+++def _delete_access_point(ap_id):+ if ap_id not in _access_points:+ return _error(404, "AccessPointNotFound", f"Access point '{ap_id}' does not exist.")+ del _access_points[ap_id]+ return _json(204, {})+++# ---------------------------------------------------------------------------+# Tags+# ---------------------------------------------------------------------------++def _tag_resource(resource_id, body):+ resource = _find_resource(resource_id)+ if resource is None:+ return _error(404, "ResourceNotFound", f"Resource '{resource_id}' does not exist.")+ tags = body.get("Tags", [])+ existing = {t["Key"]: i for i, t in enumerate(resource.get("Tags", []))}+ tag_list = resource.setdefault("Tags", [])+ for tag in tags:+ idx = existing.get(tag["Key"])+ if idx is not None:+ tag_list[idx] = tag+ else:+ tag_list.append(tag)+ return _json(200, {})+++def _untag_resource(resource_id, keys):+ resource = _find_resource(resource_id)+ if resource is None:+ return _error(404, "ResourceNotFound", f"Resource '{resource_id}' does not exist.")+ resource["Tags"] = [t for t in resource.get("Tags", []) if t["Key"] not in keys]+ return _json(200, {})+++def _list_tags_for_resource(resource_id):+ resource = _find_resource(resource_id)+ if resource is None:+ return _error(404, "ResourceNotFound", f"Resource '{resource_id}' does not exist.")+ return _json(200, {"Tags": resource.get("Tags", [])})+++def _find_resource(resource_id):+ if resource_id in _file_systems:+ return _file_systems[resource_id]+ if resource_id in _access_points:+ return _access_points[resource_id]+ for fs in _file_systems.values():+ if fs["FileSystemArn"] == resource_id:+ return fs+ for ap in _access_points.values():+ if ap["AccessPointArn"] == resource_id:+ return ap+ return None+++# ---------------------------------------------------------------------------+# Lifecycle / Backup / Account (stubs)+# ---------------------------------------------------------------------------++_lifecycle_configs: dict = {}+_backup_policies: dict = {}++def _put_lifecycle_configuration(fs_id, body):+ fs = _file_systems.get(fs_id)+ if not fs:+ return _error(404, "FileSystemNotFound", f"File system '{fs_id}' does not exist.")+ _lifecycle_configs[fs_id] = body.get("LifecyclePolicies", [])+ return _json(200, {"LifecyclePolicies": _lifecycle_configs[fs_id]})+++def _describe_lifecycle_configuration(fs_id):+ fs = _file_systems.get(fs_id)+ if not fs:+ return _error(404, "FileSystemNotFound", f"File system '{fs_id}' does not exist.")+ return _json(200, {"LifecyclePolicies": _lifecycle_configs.get(fs_id, [])})+++def _put_backup_policy(fs_id, body):+ fs = _file_systems.get(fs_id)+ if not fs:+ return _error(404, "FileSystemNotFound", f"File system '{fs_id}' does not exist.")+ _backup_policies[fs_id] = body.get("BackupPolicy", {"Status": "DISABLED"})+ return _json(200, {"BackupPolicy": _backup_policies[fs_id]})+++def _describe_backup_policy(fs_id):+ fs = _file_systems.get(fs_id)+ if not fs:+ return _error(404, "FileSystemNotFound", f"File system '{fs_id}' does not exist.")+ return _json(200, {"BackupPolicy": _backup_policies.get(fs_id, {"Status": "DISABLED"})})+++def _describe_account_preferences():+ return _json(200, {"ResourceIdPreference": {"ResourceIdType": "LONG_ID", "Resources": ["FILE_SYSTEM", "MOUNT_TARGET"]}})+++def _put_account_preferences(body):+ return _json(200, {"ResourceIdPreference": {"ResourceIdType": body.get("ResourceIdType", "LONG_ID"), "Resources": ["FILE_SYSTEM", "MOUNT_TARGET"]}})+++# ---------------------------------------------------------------------------+# Request router+# ---------------------------------------------------------------------------++async def handle_request(method, path, headers, body_bytes, query_params):+ try:+ body = json.loads(body_bytes) if body_bytes else {}+ except json.JSONDecodeError:+ body = {}++ # Flatten single-value query params+ query = {k: (v[0] if isinstance(v, list) else v) for k, v in query_params.items()}++ # Strip base path prefix+ p = re.sub(r"^/2015-02-01", "", path)++ # File Systems+ if p == "/file-systems":+ if method == "POST":+ return await _a(_create_file_system(body))+ if method == "GET":+ return await _a(_describe_file_systems(query))++ m = re.fullmatch(r"/file-systems/([^/]+)", p)+ if m:+ fs_id = m.group(1)+ if method == "DELETE":+ return await _a(_delete_file_system(fs_id))+ if method == "PUT":+ return await _a(_update_file_system(fs_id, body))++ # Mount Targets+ if p == "/mount-targets":+ if method == "POST":+ return await _a(_create_mount_target(body))+ if method == "GET":+ return await _a(_describe_mount_targets(query))++ m = re.fullmatch(r"/mount-targets/([^/]+)", p)+ if m:+ mt_id = m.group(1)+ if method == "DELETE":+ return await _a(_delete_mount_target(mt_id))++ m = re.fullmatch(r"/mount-targets/([^/]+)/security-groups", p)+ if m:+ mt_id = m.group(1)+ if method == "GET":+ return await _a(_describe_mount_target_security_groups(mt_id))+ if method == "PUT":+ return await _a(_modify_mount_target_security_groups(mt_id, body))++ # Access Points+ if p == "/access-points":+ if method == "POST":+ return await _a(_create_access_point(body))+ if method == "GET":+ return await _a(_describe_access_points(query))++ m = re.fullmatch(r"/access-points/([^/]+)", p)+ if m:+ ap_id = m.group(1)+ if method == "DELETE":+ return await _a(_delete_access_point(ap_id))++ # Tags+ m = re.fullmatch(r"/resource-tags/(.+)", p)+ if m:+ resource_id = m.group(1)+ if method == "GET":+ return await _a(_list_tags_for_resource(resource_id))+ if method == "POST":+ return await _a(_tag_resource(resource_id, body))+ if method == "DELETE":+ keys = query.get("tagKeys", "").split(",") if query.get("tagKeys") else body.get("TagKeys", [])+ return await _a(_untag_resource(resource_id, keys))++ # Lifecycle+ m = re.fullmatch(r"/file-systems/([^/]+)/lifecycle-configuration", p)+ if m:+ fs_id = m.group(1)+ if method == "PUT":+ return await _a(_put_lifecycle_configuration(fs_id, body))+ if method == "GET":+ return await _a(_describe_lifecycle_configuration(fs_id))++ # Backup Policy+ m = re.fullmatch(r"/file-systems/([^/]+)/backup-policy", p)+ if m:+ fs_id = m.group(1)+ if method == "PUT":+ return await _a(_put_backup_policy(fs_id, body))+ if method == "GET":+ return await _a(_describe_backup_policy(fs_id))++ # Account Preferences+ if p == "/account-preferences":+ if method == "GET":+ return await _a(_describe_account_preferences())+ if method == "PUT":+ return await _a(_put_account_preferences(body))++ return _error(400, "InvalidAction", f"Unknown EFS path: {method} {path}")+++async def _a(result):+ return result+++# ---------------------------------------------------------------------------+# Response helpers+# ---------------------------------------------------------------------------++def _json(status, data):+ if status == 204:+ return status, {}, b""+ body = json.dumps(data).encode("utf-8")+ return status, {"Content-Type": "application/json"}, body+++def _error(status, code, message):+ body = json.dumps({"ErrorCode": code, "Message": message, "error": {"code": code}}).encode("utf-8")+ return status, {"Content-Type": "application/json", "x-amzn-errortype": code}, body+++# ---------------------------------------------------------------------------+# Reset+# ---------------------------------------------------------------------------++def reset():+ _file_systems.clear()+ _mount_targets.clear()+ _access_points.clear()+ _lifecycle_configs.clear()+ _backup_policies.clear()diff --git a/pyproject.toml b/pyproject.tomlindex a3d93110..8af1f5c1 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"[project]name = "ministack"-version = "1.1.2"+version = "1.1.3"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.pyindex 639cc672..72ea7494 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -149,6 +149,14 @@ def ec2():def emr():return make_client("emr")[email protected](scope="session")+def ebs():+ return make_client("ec2")+[email protected](scope="session")+def efs():+ return make_client("efs")+@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.pyindex 7b6f2ebe..2f8adeb3 100644--- a/tests/test_services.py+++ b/tests/test_services.py@@ -11345,3 +11345,219 @@ def test_emr_instance_groups(emr):assert len(new_group_resp["InstanceGroupIds"]) == 1groups2 = emr.list_instance_groups(ClusterId=cluster_id)assert len(groups2["InstanceGroups"]) == 3+++# ---------------------------------------------------------------------------+# EBS (Elastic Block Store) — uses ec2 client+# ---------------------------------------------------------------------------++def test_ebs_create_and_describe_volume(ebs):+ resp = ebs.create_volume(+ AvailabilityZone="us-east-1a",+ Size=20,+ VolumeType="gp3",+ )+ vol_id = resp["VolumeId"]+ assert vol_id.startswith("vol-")+ assert resp["State"] == "available"+ assert resp["Size"] == 20+ assert resp["VolumeType"] == "gp3"++ desc = ebs.describe_volumes(VolumeIds=[vol_id])+ assert len(desc["Volumes"]) == 1+ assert desc["Volumes"][0]["VolumeId"] == vol_id+++def test_ebs_attach_detach_volume(ebs):+ inst = ebs.run_instances(ImageId="ami-00000001", MinCount=1, MaxCount=1)+ instance_id = inst["Instances"][0]["InstanceId"]++ vol = ebs.create_volume(AvailabilityZone="us-east-1a", Size=10, VolumeType="gp2")+ vol_id = vol["VolumeId"]++ ebs.attach_volume(VolumeId=vol_id, InstanceId=instance_id, Device="/dev/xvdf")+ desc = ebs.describe_volumes(VolumeIds=[vol_id])+ assert desc["Volumes"][0]["State"] == "in-use"+ assert desc["Volumes"][0]["Attachments"][0]["InstanceId"] == instance_id++ ebs.detach_volume(VolumeId=vol_id)+ desc2 = ebs.describe_volumes(VolumeIds=[vol_id])+ assert desc2["Volumes"][0]["State"] == "available"+ assert desc2["Volumes"][0]["Attachments"] == []+++def test_ebs_delete_volume(ebs):+ vol = ebs.create_volume(AvailabilityZone="us-east-1a", Size=5, VolumeType="gp2")+ vol_id = vol["VolumeId"]+ ebs.delete_volume(VolumeId=vol_id)+ desc = ebs.describe_volumes(VolumeIds=[vol_id])+ assert len(desc["Volumes"]) == 0+++def test_ebs_modify_volume(ebs):+ vol = ebs.create_volume(AvailabilityZone="us-east-1a", Size=10, VolumeType="gp2")+ vol_id = vol["VolumeId"]+ resp = ebs.modify_volume(VolumeId=vol_id, Size=50, VolumeType="gp3")+ assert resp["VolumeModification"]["TargetSize"] == 50+ assert resp["VolumeModification"]["TargetVolumeType"] == "gp3"+++def test_ebs_volume_status(ebs):+ vol = ebs.create_volume(AvailabilityZone="us-east-1a", Size=8, VolumeType="gp2")+ vol_id = vol["VolumeId"]+ resp = ebs.describe_volume_status(VolumeIds=[vol_id])+ assert len(resp["VolumeStatuses"]) == 1+ assert resp["VolumeStatuses"][0]["VolumeStatus"]["Status"] == "ok"+++def test_ebs_create_and_describe_snapshot(ebs):+ vol = ebs.create_volume(AvailabilityZone="us-east-1a", Size=10, VolumeType="gp2")+ vol_id = vol["VolumeId"]+ snap = ebs.create_snapshot(VolumeId=vol_id, Description="test snapshot")+ snap_id = snap["SnapshotId"]+ assert snap_id.startswith("snap-")+ assert snap["State"] == "completed"++ desc = ebs.describe_snapshots(SnapshotIds=[snap_id])+ assert len(desc["Snapshots"]) == 1+ assert desc["Snapshots"][0]["VolumeId"] == vol_id+ assert desc["Snapshots"][0]["Description"] == "test snapshot"+++def test_ebs_delete_snapshot(ebs):+ vol = ebs.create_volume(AvailabilityZone="us-east-1a", Size=10, VolumeType="gp2")+ snap = ebs.create_snapshot(VolumeId=vol["VolumeId"])+ snap_id = snap["SnapshotId"]+ ebs.delete_snapshot(SnapshotId=snap_id)+ desc = ebs.describe_snapshots(SnapshotIds=[snap_id])+ assert len(desc["Snapshots"]) == 0+++def test_ebs_copy_snapshot(ebs):+ vol = ebs.create_volume(AvailabilityZone="us-east-1a", Size=10, VolumeType="gp2")+ snap = ebs.create_snapshot(VolumeId=vol["VolumeId"], Description="original")+ snap_id = snap["SnapshotId"]+ copy = ebs.copy_snapshot(SourceRegion="us-east-1", SourceSnapshotId=snap_id, Description="copy")+ new_snap_id = copy["SnapshotId"]+ assert new_snap_id != snap_id+ assert new_snap_id.startswith("snap-")+++# ---------------------------------------------------------------------------+# EFS (Elastic File System)+# ---------------------------------------------------------------------------++def test_efs_create_and_describe_filesystem(efs):+ resp = efs.create_file_system(+ PerformanceMode="generalPurpose",+ ThroughputMode="bursting",+ Encrypted=False,+ Tags=[{"Key": "Name", "Value": "test-fs"}],+ )+ fs_id = resp["FileSystemId"]+ assert fs_id.startswith("fs-")+ assert resp["LifeCycleState"] == "available"+ assert resp["ThroughputMode"] == "bursting"++ desc = efs.describe_file_systems(FileSystemId=fs_id)+ assert len(desc["FileSystems"]) == 1+ assert desc["FileSystems"][0]["FileSystemId"] == fs_id+ assert desc["FileSystems"][0]["Name"] == "test-fs"+++def test_efs_creation_token_idempotency(efs):+ token = "unique-token-abc123"+ r1 = efs.create_file_system(CreationToken=token)+ r2 = efs.create_file_system(CreationToken=token)+ assert r1["FileSystemId"] == r2["FileSystemId"]+++def test_efs_delete_filesystem(efs):+ resp = efs.create_file_system()+ fs_id = resp["FileSystemId"]+ efs.delete_file_system(FileSystemId=fs_id)+ desc = efs.describe_file_systems(FileSystemId=fs_id)+ assert len(desc["FileSystems"]) == 0+++def test_efs_mount_target(efs):+ fs = efs.create_file_system()+ fs_id = fs["FileSystemId"]+ mt = efs.create_mount_target(FileSystemId=fs_id, SubnetId="subnet-00000001")+ mt_id = mt["MountTargetId"]+ assert mt_id.startswith("fsmt-")+ assert mt["LifeCycleState"] == "available"++ desc = efs.describe_mount_targets(FileSystemId=fs_id)+ assert len(desc["MountTargets"]) == 1+ assert desc["MountTargets"][0]["MountTargetId"] == mt_id++ import botocore.exceptions+ try:+ efs.delete_file_system(FileSystemId=fs_id)+ assert False, "should raise"+ except botocore.exceptions.ClientError as e:+ assert e.response["Error"]["Code"] in ("FileSystemInUse", "400") or "mount targets" in str(e).lower()++ efs.delete_mount_target(MountTargetId=mt_id)+ desc2 = efs.describe_mount_targets(FileSystemId=fs_id)+ assert len(desc2["MountTargets"]) == 0+++def test_efs_access_point(efs):+ fs = efs.create_file_system()+ fs_id = fs["FileSystemId"]+ ap = efs.create_access_point(+ FileSystemId=fs_id,+ Tags=[{"Key": "Name", "Value": "my-ap"}],+ RootDirectory={"Path": "/data"},+ )+ ap_id = ap["AccessPointId"]+ assert ap_id.startswith("fsap-")+ assert ap["LifeCycleState"] == "available"++ desc = efs.describe_access_points(FileSystemId=fs_id)+ assert any(a["AccessPointId"] == ap_id for a in desc["AccessPoints"])++ efs.delete_access_point(AccessPointId=ap_id)+ desc2 = efs.describe_access_points(FileSystemId=fs_id)+ assert not any(a["AccessPointId"] == ap_id for a in desc2["AccessPoints"])+++def test_efs_tags(efs):+ fs = efs.create_file_system(Tags=[{"Key": "env", "Value": "test"}])+ fs_arn = fs["FileSystemArn"]+ efs.tag_resource(ResourceId=fs_arn, Tags=[{"Key": "team", "Value": "data"}])+ tags_resp = efs.list_tags_for_resource(ResourceId=fs_arn)+ tag_map = {t["Key"]: t["Value"] for t in tags_resp["Tags"]}+ assert tag_map["env"] == "test"+ assert tag_map["team"] == "data"++ efs.untag_resource(ResourceId=fs_arn, TagKeys=["env"])+ tags_resp2 = efs.list_tags_for_resource(ResourceId=fs_arn)+ keys = [t["Key"] for t in tags_resp2["Tags"]]+ assert "env" not in keys+ assert "team" in keys+++def test_efs_lifecycle_configuration(efs):+ fs = efs.create_file_system()+ fs_id = fs["FileSystemId"]+ efs.put_lifecycle_configuration(+ FileSystemId=fs_id,+ LifecyclePolicies=[{"TransitionToIA": "AFTER_30_DAYS"}],+ )+ resp = efs.describe_lifecycle_configuration(FileSystemId=fs_id)+ assert len(resp["LifecyclePolicies"]) == 1+ assert resp["LifecyclePolicies"][0]["TransitionToIA"] == "AFTER_30_DAYS"+++def test_efs_backup_policy(efs):+ fs = efs.create_file_system()+ fs_id = fs["FileSystemId"]+ efs.put_backup_policy(+ FileSystemId=fs_id,+ BackupPolicy={"Status": "ENABLED"},+ )+ resp = efs.describe_backup_policy(FileSystemId=fs_id)+ assert resp["BackupPolicy"]["Status"] == "ENABLED"