Files
floci/docs/services/ec2.md
T
Michal Schreiber 74e43a4632 feat(ec2): support transit gateway VPC attachments (#2347)
* feat(ec2): support transit gateway VPC attachments

CreateTransitGatewayVpcAttachment, DescribeTransitGatewayVpcAttachments,
DescribeTransitGatewayAttachments, ModifyTransitGatewayVpcAttachment and
DeleteTransitGatewayVpcAttachment. Part two of #2308, on top of the
gateway itself.

The two describes are separate shapes rather than one being a superset:
the VPC-specific form carries the subnets and options, while the
resource-agnostic form drops both, types the VPC as a resource, and is
the only place the route table association appears.

Behaviour taken from a live account rather than the reference. The
attachment's option defaults are its own: dnsSupport and
securityGroupReferencingSupport enabled, ipv6Support and
applianceModeSupport disabled. The second of those is enabled here while
the gateway that owns the attachment defaults it to disabled, which is
not something the documentation calls out.

An attachment associates with the gateway's default route table only when
the gateway asks for it, and an association already made survives the
gateway later disabling that default: the association belongs to the
attachment from creation, and only later attachments are affected.

Rejections, all as observed: a VPC attached twice to one gateway is
DuplicateTransitGatewayAttachment, two subnets in one zone are
DuplicateSubnetsInSameZone, a subnet from another VPC is reported missing
rather than mismatched, removing a subnet that is not attached is
InvalidSubnetID.NotFound with its own wording, and removing the last one
is InsufficientSubnetsException. A malformed attachment id is rejected
before the lookup, with the terse message the real API uses.

Two changes reach outside the new surface, both deliberate:

DeleteTransitGateway now refuses while attachments exist, reporting
IncorrectState and naming them. Part one could not have hit this, since
nothing could attach then.

parseTagsForResource reads TagSpecifications as well as TagSpecification.
CreateTransitGatewayVpcAttachment declares no locationName on that member
and so serializes the plural, unlike its neighbours; every tag sent by
the AWS CLI was being dropped. The change only adds a spelling, so
actions using the singular are untouched.

State is reported settled rather than transitional, as for the gateway.
Ipv6Support is accepted without checking that the subnets carry IPv6
CIDRs, which real AWS rejects; Floci does not model subnet IPv6
allocation, and inventing that state to enforce it seemed worse than
documenting the gap.

* fix(ec2): make attachment uniqueness atomic and guard attached resources

Two defects in the VPC attachment work, both found in review.

The one-attachment-per-VPC rule scanned for an existing attachment and
then stored the new one without holding a lock between the two, so
concurrent creates for the same VPC could all find nothing and all
persist. Reproduced by disabling the fix: eight threads, eight
attachments, where the API promises one. The check and the write now
share the gateway's lock, and the test asserts one winner, the right
error for every loser, and one stored attachment, over forty trials.

Deleting a VPC or a subnet that an attachment uses left the attachment
naming resources that no longer existed, which surfaced later as a modify
failing on a subnet the caller never touched. Checked on a live account:
both refuse, with the same code and shape of message.

  DependencyViolation: The subnet 'subnet-…' has dependencies and cannot
  be deleted.
  DependencyViolation: The vpc 'vpc-…' has dependencies and cannot be
  deleted.

Both deletes now refuse the same way. A subnet of the attached VPC that
the attachment does not use still deletes, so the guard is no wider than
the dependency it protects.

* test(ec2): lighten the attachment concurrency harness

Forty trials of eight threads was heavier than the race needs — without
the lock it shows on the first trial — and the extra load disturbed two
thread-timing-sensitive tests elsewhere in the suite,
PostgresProtocolHandlerTest and ElbV2HealthCheckerTest, neither of which
this branch touches. Ten trials of six still reproduces it and leaves
those alone.

* fix(ec2): guard everything an attachment depends on under one lock

The previous fix locked the uniqueness check alone, which was too narrow
twice over. The gateway was resolved before the locked section, so a
concurrent DeleteTransitGateway could see no attachments, delete the
gateway, and let the create persist against the object it had already
read. The VPC and subnet checks were outside any shared lock at all, and
lockFor is striped, so a gateway's monitor never guarded a VPC or subnet
delete regardless.

Everything an attachment depends on now resolves and writes under one
region-scoped monitor: the gateway, the VPC, the subnets, and the
uniqueness rule. Deleting a gateway, a VPC or a subnet takes the same
monitor across its dependency check and its delete. Where a gateway lock
is also taken it is acquired inside this one, so the two cannot
interleave in opposite orders.

The test races a create against each delete and asserts the invariant
rather than a winner: whoever wins, the store must never hold an
attachment naming a gateway, VPC or subnet that is gone. It reproduces
both holes — with the create-side lock removed, "attachment outlived its
gateway" fails on the first trial.

* fix(ec2): stop a tag write restoring a deleted transit gateway resource

Tagging is a read-modify-write, so a tag call overlapping a delete could
read the record, lose the race, and put it back afterwards. A resurrected
attachment goes on blocking the VPC and subnets it names; a resurrected
gateway goes on refusing its own deletion. The gateway and route table
branches were as exposed as the attachment one, so all three moved
together rather than only the case reported.

Ordering matters as much as the lock here. The deletes take the topology
lock and then a striped resource lock, so the tag paths have to take them
the same way round; taking the topology lock further down the stack, with
the resource lock already held, deadlocks against a concurrent delete.
That is what the first attempt did, and the race test caught it as a pool
that never drained. createTags and deleteTags now take the topology lock
outermost for tgw- resources and updateResourceTags relies on its callers
for it.

The test races tagging against deletion for an attachment and for a
gateway, asserting neither comes back.
2026-08-18 07:05:24 -04:00

550 lines
28 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# EC2
**Protocol:** EC2 Query (XML) — `POST http://localhost:4566/` with `Action=` parameter
## Instance Execution Model
`RunInstances` launches a **real Docker container** for each instance. By default, the container is kept alive with `tail -f /dev/null` so any base image works regardless of its default CMD. Catalog entries that opt into the `systemd` guest runtime start `/sbin/init` instead, with the Docker mounts needed for a systemd-based cloud-image guest.
| EC2 state | Docker operation |
|---|---|
| `pending → running` | Container created and started |
| `running → stopping → stopped` | `docker stop` (30 s timeout, then SIGKILL) |
| `stopped → pending → running` | `docker start` |
| `running → shutting-down → terminated` | `docker rm -f` |
| Reboot | `docker restart` |
Terminated instances remain queryable for 1 hour (matching real EC2 tombstone behavior) before being pruned.
## AMI to Docker Image Mapping
Floci resolves AMI IDs to Docker images from the EC2 image catalog at
`src/main/resources/ec2/image-catalog.yaml`. The same catalog stores the
fallback Docker image, per-AMI Docker image mappings, and `DescribeImages`
metadata.
| AMI ID | Aliases | Docker image |
|---|---|---|
| `ami-0abcdef1234567890` | `ami-amazonlinux2` | `public.ecr.aws/amazonlinux/amazonlinux:2` |
| `ami-0abcdef1234567891` | `ami-amazonlinux2023` | `public.ecr.aws/amazonlinux/amazonlinux:2023` |
| `ami-0abcdef1234567892` | `ami-ubuntu2004` | `public.ecr.aws/docker/library/ubuntu:20.04` |
| `ami-ubuntu2204` | | `public.ecr.aws/docker/library/ubuntu:22.04` |
| `ami-ubuntu2404-arm64` | `ami-ubuntu2404` | `public.ecr.aws/docker/library/ubuntu:24.04` |
| `ami-ubuntu2404-amd64` | | `public.ecr.aws/docker/library/ubuntu:24.04` |
| `ami-ubuntu2404-cloud-arm64` | `ami-ubuntu2404-cloud` | `floci/ami-ubuntu:24.04-arm64` |
| `ami-debian12` | | `public.ecr.aws/docker/library/debian:12` |
| `ami-alpine` | | `public.ecr.aws/docker/library/alpine:latest` |
| `ami-0abcdef1234567893` | | `public.ecr.aws/amazonlinux/amazonlinux:2023` |
Any unrecognized AMI ID (including real AWS AMI IDs like `ami-0abc12345678`) falls back to the catalog `defaultDockerImage` (`public.ecr.aws/amazonlinux/amazonlinux:2023` by default).
### Cloud-image-derived AMI guests
The `ami-ubuntu2404-cloud` entry is an experimental Ubuntu 24.04 guest image built from Canonical cloud-image artifacts, not from the Docker-library `ubuntu:24.04` image. It is intended for EC2 workflows that need packages such as `systemd` and `cloud-init` to match a real Ubuntu cloud image more closely.
This mode is opt-in by AMI selection, not by a global configuration switch.
Existing catalog entries, including `ami-ubuntu2404`, keep their current
Docker-library image mapping and default `tail -f /dev/null` container
lifecycle. The cloud-image-derived entry is a separate AMI ID and alias, so
`DescribeImages` can advertise it while existing callers continue to get the
old behavior unless they choose `ami-ubuntu2404-cloud-arm64` or the
`ami-ubuntu2404-cloud` alias.
The Java metadata-driven builder lives at `io.github.hectorvent.floci.tools.ami.AmiImageTool`. Its recipe is checked in at `docker/ec2/ami-images/image-build-metadata.yaml`, and generated context/provenance defaults to `target/ami-images/<image-id>/`.
```bash
./mvnw -q -DskipTests compile exec:java \
-Dexec.mainClass=io.github.hectorvent.floci.tools.ami.AmiImageTool \
-Dexec.args="plan --image-id ubuntu-24.04-arm64"
./mvnw -q -DskipTests compile exec:java \
-Dexec.mainClass=io.github.hectorvent.floci.tools.ami.AmiImageTool \
-Dexec.args="generate --image-id ubuntu-24.04-arm64"
./mvnw -q -DskipTests compile exec:java \
-Dexec.mainClass=io.github.hectorvent.floci.tools.ami.AmiImageTool \
-Dexec.args="build --image-id ubuntu-24.04-arm64"
./mvnw -q -DskipTests compile exec:java \
-Dexec.mainClass=io.github.hectorvent.floci.tools.ami.AmiImageTool \
-Dexec.args="smoke --image-id ubuntu-24.04-arm64"
```
## SSH Key Injection
If `KeyName` is specified at launch, Floci looks up the stored key pair's public key material (set via `ImportKeyPair`) and copies it into `/root/.ssh/authorized_keys` inside the container at boot. It then attempts to start `sshd` if present. The SSH port (container port 22) is mapped to a host port from the configured range (default 2200–2299).
Key pairs created with `CreateKeyPair` contain dummy private key material. Import a real key pair with `ImportKeyPair` to enable working SSH access.
## Security Group Port Publishing
When an instance's security groups open a TCP port to a CIDR source, Floci publishes that port on the host so you can reach the app from `localhost`. For each opened port Floci starts a small `alpine/socat` sidecar container that binds an allocated host port (default range 30000–30999) and forwards it to the instance container's IP. This works both for rules present at launch and for rules added later with `authorize-security-group-ingress`; revoking the rule removes the forward. The mapping (`app port -> host port`) is written to the logs:
```
Published EC2 instance i-0abc... app port 80 on host port 30000 (socat -> 172.17.0.3:80)
```
Notes and limitations:
- The app inside the instance must listen on `0.0.0.0` (not `127.0.0.1`) for the forward to reach it.
- Only CIDR-sourced TCP rules are published. A port opened only to a referenced security group (or via a prefix list) is not published, matching AWS: those grant reachability from the referenced group's private IPs, not from the host. The source CIDR value itself is not enforced, so a CIDR-sourced port is reachable whether the rule is `0.0.0.0/0` or narrower.
- Ports are aggregated across all of the instance's security groups, SSH (22) is never re-forwarded, and any single rule whose port span exceeds `max-published-ports-per-instance` (default 20) is skipped so an allow-all range cannot spawn thousands of sidecars. The total published per instance is capped at the same limit.
- Stopping an instance tears down its forwards; starting it again does not automatically restore them (re-run `authorize-security-group-ingress`, or recreate the instance).
- Set `publish-security-group-ports: false` (`FLOCI_SERVICES_EC2_PUBLISH_SECURITY_GROUP_PORTS=false`) to keep security groups as metadata only.
## UserData
`UserData` must be base64-encoded in the request (matching the AWS wire format). Floci decodes it, copies the script into `/tmp/user-data.sh` inside the container, and executes the script directly after SSH key injection so the script shebang selects the interpreter. Output is captured and logged.
EC2 containers receive `AWS_EC2_METADATA_SERVICE_ENDPOINT` for IMDS and `AWS_ENDPOINT_URL` for AWS service API calls back to Floci.
## Instance Metadata Service (IMDS)
Floci runs an IMDS-compatible HTTP server on port `9169` of the host. Each launched container receives the environment variable `AWS_EC2_METADATA_SERVICE_ENDPOINT` pointing to this server.
Both IMDSv1 (no token) and IMDSv2 (token-based) flows are supported:
```bash
# IMDSv2 — get a token first
TOKEN=$(curl -s -X PUT "http://169.254.169.254/latest/api/token" \
-H "x-aws-ec2-metadata-token-ttl-seconds: 21600")
# Then use the token for metadata requests
curl -s -H "x-aws-ec2-metadata-token: $TOKEN" \
http://169.254.169.254/latest/meta-data/instance-id
```
### Supported IMDS endpoints
| Endpoint | Returns |
|---|---|
| `GET /latest/meta-data/instance-id` | Instance ID |
| `GET /latest/meta-data/ami-id` | Image ID |
| `GET /latest/meta-data/instance-type` | Instance type |
| `GET /latest/meta-data/local-ipv4` | Private IP |
| `GET /latest/meta-data/public-ipv4` | Public IP (`127.0.0.1`) |
| `GET /latest/meta-data/public-hostname` | Public hostname |
| `GET /latest/meta-data/local-hostname` | Private DNS name |
| `GET /latest/meta-data/hostname` | Private DNS name |
| `GET /latest/meta-data/mac` | MAC address of first ENI |
| `GET /latest/meta-data/security-groups` | Security group names |
| `GET /latest/meta-data/placement/availability-zone` | AZ |
| `GET /latest/meta-data/placement/region` | Region |
| `GET /latest/meta-data/iam/info` | IAM instance profile info |
| `GET /latest/meta-data/iam/security-credentials/` | Role name list |
| `GET /latest/meta-data/iam/security-credentials/{role}` | Temporary credentials |
| `GET /latest/user-data` | UserData script |
| `GET /latest/dynamic/instance-identity/document` | Identity document JSON |
IAM credentials are served when the instance has an `IamInstanceProfile.Arn` set at launch. The container can then call other Floci services with full SigV4 validation using the standard AWS SDK credential chain.
## Default Resources
Floci seeds the following resources on first use in each region so Terraform, the AWS CLI, and SDK clients work out of the box without any setup:
| Resource | ID | Details |
|---|---|---|
| Default VPC | `vpc-default` | CIDR `172.31.0.0/16` |
| Default Subnet (AZ a) | `subnet-default-a` | CIDR `172.31.0.0/20` |
| Default Subnet (AZ b) | `subnet-default-b` | CIDR `172.31.16.0/20` |
| Default Subnet (AZ c) | `subnet-default-c` | CIDR `172.31.32.0/20` |
| Default Security Group | `sg-default` | `groupName=default`, all-traffic egress |
| Default Internet Gateway | `igw-default` | Attached to default VPC |
| Main Route Table | `rtb-default` | Associated with default VPC |
| Default Network ACL | `acl-default` | Allow-all, associated with the default subnets |
## Supported Actions
### Instances
| Action | Description |
|--------|-------------|
| RunInstances | Creates one or more local EC2 instances, starting Docker-backed runtime when not in mock mode. |
| DescribeInstances | Lists or returns stored EC2 instances. |
| TerminateInstances | Terminates instances and updates their stored lifecycle state. |
| StartInstances | Starts stopped instances and their local runtime when applicable. |
| StopInstances | Stops running instances and updates their stored lifecycle state. |
| RebootInstances | Reboots instances through the local EC2 service model. |
| DescribeInstanceStatus | Returns status records for stored instances. |
| DescribeInstanceAttribute | Returns a supported attribute for an instance. |
| ModifyInstanceAttribute | Updates supported mutable attributes for an instance. |
### VPCs
| Action | Description |
|--------|-------------|
| CreateVpc | Creates a VPC with the requested CIDR block. |
| DescribeVpcs | Lists or returns stored VPCs. |
| DeleteVpc | Deletes a VPC from the local EC2 store. |
| ModifyVpcAttribute | Updates supported VPC attributes. |
| DescribeVpcAttribute | Returns a supported VPC attribute. |
| DescribeVpcEndpointServices | Returns an empty local VPC endpoint service catalog. |
| CreateVpcEndpoint | Creates a VPC endpoint record. |
| DescribeVpcEndpoints | Lists or returns stored VPC endpoints. |
| DeleteVpcEndpoints | Deletes VPC endpoint records. |
| CreateDefaultVpc | Creates or returns the default VPC for the region. |
| AssociateVpcCidrBlock | Adds a secondary CIDR block association to a VPC. |
| DisassociateVpcCidrBlock | Removes a secondary CIDR block association from a VPC. |
### Subnets
| Action | Description |
|--------|-------------|
| CreateSubnet | Creates a subnet in a VPC. |
| DescribeSubnets | Lists or returns stored subnets. |
| DeleteSubnet | Deletes a subnet from the local EC2 store. |
| ModifySubnetAttribute | Updates supported subnet attributes. |
### Security Groups
| Action | Description |
|--------|-------------|
| CreateSecurityGroup | Creates a security group in a VPC. |
| DescribeSecurityGroups | Lists or returns stored security groups. |
| DeleteSecurityGroup | Deletes a security group from the local EC2 store. |
| AuthorizeSecurityGroupIngress | Adds inbound permissions. Sources may be IPv4 ranges, IPv6 ranges, or another security group (`UserIdGroupPairs`, sent on the wire as `Groups`); prefix list sources are not stored. One rule is stored per source, each carrying its own description. |
| AuthorizeSecurityGroupEgress | Adds outbound permissions, with the same source types as the inbound call. |
| RevokeSecurityGroupIngress | Removes inbound permissions. Matches on protocol and port range only, so it removes every permission on that port regardless of source. |
| RevokeSecurityGroupEgress | Removes outbound permissions, matched the same way as the inbound call. |
| DescribeSecurityGroupRules | Lists stored security group rules. |
| ModifySecurityGroupRules | Updates supported fields on security group rules. |
| UpdateSecurityGroupRuleDescriptionsIngress | Updates descriptions on matching inbound security group rules. |
| UpdateSecurityGroupRuleDescriptionsEgress | Updates descriptions on matching outbound security group rules. |
### Key Pairs
| Action | Description |
|--------|-------------|
| CreateKeyPair | Creates and stores a local key pair. |
| DescribeKeyPairs | Lists or returns stored key pairs. |
| DeleteKeyPair | Deletes a key pair from the local EC2 store. |
| ImportKeyPair | Imports a public key as a local key pair. |
### AMIs
| Action | Description |
|--------|-------------|
| DescribeImages | Returns AMI metadata known to the local EC2 service. |
| CreateImage | Captures an instance as a new AMI. Reboots the source unless `NoReboot=true`. |
| RegisterImage | Registers an AMI from supplied metadata and block device mappings. |
### Tags
| Action | Description |
|--------|-------------|
| CreateTags | Adds tags to supported EC2 resources. |
| DeleteTags | Removes tags from supported EC2 resources. |
| DescribeTags | Lists tags stored for EC2 resources. |
### Internet Gateways
| Action | Description |
|--------|-------------|
| CreateInternetGateway | Creates an internet gateway. |
| DescribeInternetGateways | Lists or returns stored internet gateways. |
| DeleteInternetGateway | Deletes an internet gateway. |
| AttachInternetGateway | Attaches an internet gateway to a VPC. |
| DetachInternetGateway | Detaches an internet gateway from a VPC. |
### Route Tables
| Action | Description |
|--------|-------------|
| CreateRouteTable | Creates a route table in a VPC. |
| DescribeRouteTables | Lists or returns stored route tables. |
| DeleteRouteTable | Deletes a route table from the local EC2 store. |
| AssociateRouteTable | Associates a route table with a subnet. |
| DisassociateRouteTable | Removes a route table association. |
| CreateRoute | Adds a route to a route table. |
| ReplaceRoute | Replaces the target of an existing route. |
| DeleteRoute | Removes a route from a route table. |
### Network ACLs
| Action | Description |
|--------|-------------|
| CreateNetworkAcl | Creates a network ACL in a VPC. |
| DescribeNetworkAcls | Lists or returns stored network ACLs. |
| DeleteNetworkAcl | Deletes a network ACL from the local EC2 store. |
| CreateNetworkAclEntry | Adds an entry to a network ACL. |
| ReplaceNetworkAclEntry | Replaces an entry in a network ACL. |
| DeleteNetworkAclEntry | Removes an entry from a network ACL. |
| ReplaceNetworkAclAssociation | Replaces the network ACL associated with a subnet. |
### Prefix Lists
| Action | Description |
|--------|-------------|
| DescribePrefixLists | Returns prefix lists known to the local EC2 service. |
| CreateManagedPrefixList | Creates a customer-managed prefix list with its initial entries. |
| DescribeManagedPrefixLists | Lists customer-managed and AWS-managed prefix lists. |
| GetManagedPrefixListEntries | Returns the entries of a prefix list, optionally at an earlier version. |
| ModifyManagedPrefixList | Adds or removes entries, renames the list, or raises its entry limit. |
| DeleteManagedPrefixList | Deletes a customer-managed prefix list. |
Two AWS-managed prefix lists exist in every region without being created —
`com.amazonaws.<region>.s3` (`pl-63a5400a`) and `com.amazonaws.<region>.dynamodb`
(`pl-02cd2c6b`) — matching the gateway endpoint services on AWS. They are owned by `AWS`,
read-only, and served by both `DescribePrefixLists` and `DescribeManagedPrefixLists`;
modifying or deleting one returns `UnsupportedOperation`.
A customer-managed list may not take a name AWS reserves for its own: `com.amazonaws.`,
`com.amazon.` or `com.aws.`, each including the trailing dot. `CreateManagedPrefixList`
rejects those with `InvalidParameterValue`; a name that merely resembles one, such as
`com.amazonaws-internal`, is allowed.
Entries are versioned. A prefix list starts at version 1, and each `ModifyManagedPrefixList`
that adds or removes entries stores a new version and bumps the counter, so
`GetManagedPrefixListEntries` can serve an earlier `TargetVersion`. Renaming the list or
changing `MaxEntries` does not create a version. Passing `CurrentVersion` makes the
modification conditional: a stale value returns `PrefixListVersionMismatch`. Removals are applied before
additions, so one call can replace an entry's description by removing and re-adding the CIDR.
Creation is synchronous: a new list is returned as `create-complete` rather than passing
through `create-in-progress`, since nothing about it is slow locally.
A security group rule can take a prefix list as its source instead of a CIDR. Pass it as
`IpPermissions.N.PrefixListIds.M.PrefixListId`, optionally with a `Description`; AWS emits one rule
per source, so a permission naming both CIDRs and prefix lists expands to a rule for each. The
resulting rule carries `prefixListId` in place of `cidrIpv4`, and `DescribeSecurityGroups` nests
the reference under the permission as `prefixListIds`. Authorizing against a list that does not
exist returns `InvalidPrefixListID.NotFound`, so a typo cannot leave a rule pointing at nothing.
### Transit Gateways
| Action | Description |
|--------|-------------|
| CreateTransitGateway | Creates a transit gateway, applying AWS's option defaults and minting its default route table. |
| DescribeTransitGateways | Lists or returns stored transit gateways. |
| ModifyTransitGateway | Updates a transit gateway's description, options and CIDR blocks. |
| DeleteTransitGateway | Deletes a transit gateway and the default route table created with it. |
Transit gateway metadata only: nothing routes packets, and the value is in ids that later
resources can reference and describes that round-trip so plans converge.
Options left out of `CreateTransitGateway` take the same defaults AWS applies — `amazonSideAsn`
64512, `dnsSupport`, `vpnEcmpSupport`, `defaultRouteTableAssociation` and
`defaultRouteTablePropagation` enabled, and `autoAcceptSharedAttachments`,
`securityGroupReferencingSupport` and `multicastSupport` disabled. `transitGatewayCidrBlocks` is
omitted from the response entirely when no blocks are set, rather than sent empty.
Creating a gateway with either default-route-table option enabled also creates the route table
AWS creates, and reports its id as `associationDefaultRouteTableId` and
`propagationDefaultRouteTableId`. Both name the same table. Disabling both leaves the ids absent.
The actions that operate on transit gateway route tables directly — creating them, associating
attachments, enabling propagation — are not implemented yet, and neither are attachments.
State is reported settled rather than transitional: AWS returns a new gateway as `pending` and
reaches `available` roughly a minute later, and reports `deleting` before `deleted`. Nothing here
is slow, so callers see `available` and `deleted` immediately. `ModifyTransitGateway` and
`DeleteTransitGateway` echo the gateway without its `tagSet`, matching AWS; `CreateTransitGateway`
and `DescribeTransitGateways` include it.
### Transit Gateway VPC Attachments
| Action | Description |
|--------|-------------|
| CreateTransitGatewayVpcAttachment | Attaches a VPC to a transit gateway through one subnet per availability zone. |
| DescribeTransitGatewayVpcAttachments | Lists or returns VPC attachments with their subnets and options. |
| DescribeTransitGatewayAttachments | Returns the same attachments in the resource-agnostic shape, including the route table association. |
| ModifyTransitGatewayVpcAttachment | Adds or removes attachment subnets and updates its options. |
| DeleteTransitGatewayVpcAttachment | Deletes a VPC attachment. |
An attachment's option defaults are its own rather than the gateway's: `dnsSupport` and
`securityGroupReferencingSupport` enabled, `ipv6Support` and `applianceModeSupport` disabled. Note
that `securityGroupReferencingSupport` is enabled here while a transit gateway defaults it to
disabled.
The attachment is associated with the gateway's default route table only when the gateway carries
`defaultRouteTableAssociation` enabled; a gateway created without it produces an attachment with no
association. That association is reported by `DescribeTransitGatewayAttachments` alone — the
VPC-specific describe does not carry it, and the resource-agnostic one carries neither the subnets
nor the options in exchange.
Subnets must belong to the VPC being attached and no two may share an availability zone; one from
another VPC is reported as `InvalidSubnetID.NotFound` rather than as a mismatch. A VPC can be
attached to a given gateway once, so a second attempt returns `DuplicateTransitGatewayAttachment`.
Removing every subnet returns `InsufficientSubnetsException`, and a gateway with a live attachment
cannot be deleted — `IncorrectState`, naming the attachments.
As with the gateway itself, state is reported settled rather than transitional, and the echoes are
trimmed the way AWS trims them: modify omits the `tagSet`, and delete omits both the `tagSet` and
the subnets. `Ipv6Support` is accepted without checking that the subnets carry IPv6 CIDRs, which
real AWS rejects; Floci does not model subnet IPv6 allocation.
### NAT Gateways
| Action | Description |
|--------|-------------|
| CreateNatGateway | Creates a NAT gateway record. |
| DescribeNatGateways | Lists or returns stored NAT gateways. |
| DeleteNatGateway | Deletes a NAT gateway record. |
### Elastic IPs
| Action | Description |
|--------|-------------|
| AllocateAddress | Allocates an Elastic IP address record. |
| DescribeAddresses | Lists or returns stored Elastic IP address records. |
| DescribeAddressesAttribute | Returns allocation ID and public IP attributes for Elastic IP addresses. |
| AssociateAddress | Associates an Elastic IP address with a resource. |
| DisassociateAddress | Removes an Elastic IP address association. |
| ReleaseAddress | Releases an Elastic IP address record. |
### Availability Zones & Regions
| Action | Description |
|--------|-------------|
| DescribeAvailabilityZones | Returns the configured local availability zones. |
| DescribeRegions | Returns the regions known to the local EC2 service. |
| DescribeAccountAttributes | Returns local account-level EC2 attributes. |
### Instance Types
| Action | Description |
|--------|-------------|
| DescribeInstanceTypes | Returns instance type metadata known to the local EC2 service. |
| DescribeInstanceTypeOfferings | Returns instance type offerings for the requested location filters. |
### Launch Templates
| Action | Description |
|--------|-------------|
| CreateLaunchTemplate | Creates a launch template with an initial version. |
| CreateLaunchTemplateVersion | Creates a new launch template version, optionally from a source version. |
| DescribeLaunchTemplates | Lists or returns stored launch templates. |
| DescribeLaunchTemplateVersions | Lists versions stored for a launch template. |
| ModifyLaunchTemplate | Updates launch template metadata such as the default version. |
| DeleteLaunchTemplate | Deletes a launch template and its versions. |
Launch templates store versioned launch data. New template versions can be created from an existing source version, and `ModifyLaunchTemplate` updates the default version used by later launches.
### IAM Instance Profiles
| Action | Description |
|--------|-------------|
| DescribeIamInstanceProfileAssociations | Lists IAM instance profile associations known to the local EC2 service. |
### Network Interfaces
| Action | Description |
|--------|-------------|
| DescribeNetworkInterfaces | Lists network interfaces known to the local EC2 service. |
### Volumes
| Action | Description |
|--------|-------------|
| CreateVolume | Creates an EBS volume record. |
| DescribeVolumes | Lists or returns stored EBS volume records. |
| DeleteVolume | Deletes an EBS volume record. |
## Configuration
| Environment variable | Default | Description |
|---|---|---|
| `FLOCI_SERVICES_EC2_IMDS_PORT` | `9169` | Host port for the IMDS server |
| `FLOCI_SERVICES_EC2_SSH_PORT_RANGE_START` | `2200` | Start of SSH host port range |
| `FLOCI_SERVICES_EC2_SSH_PORT_RANGE_END` | `2299` | End of SSH host port range |
| `FLOCI_SERVICES_EC2_PUBLISH_SECURITY_GROUP_PORTS` | `true` | Publish security-group TCP ingress ports on the host via socat sidecars |
| `FLOCI_SERVICES_EC2_APP_PORT_RANGE_START` | `30000` | Start of the host-port range for published app ports |
| `FLOCI_SERVICES_EC2_APP_PORT_RANGE_END` | `30999` | End of the host-port range for published app ports |
| `FLOCI_SERVICES_EC2_MAX_PUBLISHED_PORTS_PER_INSTANCE` | `20` | Max published ports per instance; also the widest single-rule span published |
| `FLOCI_SERVICES_EC2_SOCAT_IMAGE` | `alpine/socat` | Image used for the port-forwarding sidecar |
| `FLOCI_SERVICES_EC2_MOCK` | `false` | Skip Docker; instances jump directly to final state (useful for tests) |
| `FLOCI_SERVICES_EC2_AWS_FAITHFUL_PRIVATE_IP` | `false` | Report the CFN/subnet-allocated private IP instead of the container bridge IP; routing and IMDS are unaffected |
## Requirements
EC2 requires the Docker socket to be accessible (same as Lambda, ECS, and other container services):
```yaml
services:
floci:
image: floci/floci:latest
ports:
- "4566:4566"
- "9169:9169" # IMDS — expose if containers need to reach it externally
volumes:
- /var/run/docker.sock:/var/run/docker.sock
```
The IMDS port (`9169`) only needs to be published if you are running EC2 containers outside the default Docker bridge network.
## Examples
```bash
export AWS_ENDPOINT_URL=http://localhost:4566
# Import an SSH key pair for injection at launch
aws ec2 import-key-pair \
--key-name my-key \
--public-key-material fileb://~/.ssh/id_rsa.pub \
--endpoint-url $AWS_ENDPOINT_URL
# Launch a real Docker container instance with UserData
aws ec2 run-instances \
--image-id ami-amazonlinux2023 \
--instance-type t2.micro \
--min-count 1 \
--max-count 1 \
--key-name my-key \
--user-data '#!/bin/bash
yum install -y nginx
systemctl start nginx' \
--endpoint-url $AWS_ENDPOINT_URL
# Launch with an IAM instance profile (credentials served via IMDS)
aws ec2 run-instances \
--image-id ami-amazonlinux2023 \
--instance-type t2.micro \
--min-count 1 \
--max-count 1 \
--iam-instance-profile Arn=arn:aws:iam::000000000000:instance-profile/my-app-role \
--endpoint-url $AWS_ENDPOINT_URL
# Describe running instances
aws ec2 describe-instances \
--filters "Name=instance-state-name,Values=running" \
--endpoint-url $AWS_ENDPOINT_URL
# Stop and start an instance
aws ec2 stop-instances --instance-ids i-XXXXX --endpoint-url $AWS_ENDPOINT_URL
aws ec2 start-instances --instance-ids i-XXXXX --endpoint-url $AWS_ENDPOINT_URL
# Terminate an instance
aws ec2 terminate-instances --instance-ids i-XXXXX --endpoint-url $AWS_ENDPOINT_URL
# Create a VPC and subnet
aws ec2 create-vpc --cidr-block 10.0.0.0/16 --endpoint-url $AWS_ENDPOINT_URL
aws ec2 create-subnet --vpc-id vpc-XXXXX --cidr-block 10.0.1.0/24 --endpoint-url $AWS_ENDPOINT_URL
# Create and configure a security group
aws ec2 create-security-group \
--group-name my-sg \
--description "My security group" \
--vpc-id vpc-XXXXX \
--endpoint-url $AWS_ENDPOINT_URL
aws ec2 authorize-security-group-ingress \
--group-id sg-XXXXX \
--protocol tcp \
--port 22 \
--cidr 0.0.0.0/0 \
--endpoint-url $AWS_ENDPOINT_URL
# Allocate and associate an Elastic IP
aws ec2 allocate-address --domain vpc --endpoint-url $AWS_ENDPOINT_URL
aws ec2 associate-address \
--allocation-id eipalloc-XXXXX \
--instance-id i-XXXXX \
--endpoint-url $AWS_ENDPOINT_URL
```
## Notes
- `DescribeImages` returns AMIs from the EC2 image catalog, including common AMIs and Floci-native AMI IDs.
- Key material returned by `CreateKeyPair` is a dummy RSA PEM — not usable for real SSH. Use `ImportKeyPair` for working SSH access.
- Security group rules are not enforced as a firewall (Docker bridge networking handles routing), but TCP ingress rules opened to a CIDR source are published on the host via socat sidecars so the instance's app is reachable from `localhost` — see [Security Group Port Publishing](#security-group-port-publishing).
- The IMDS server identifies which instance is calling via IMDSv2 tokens (mapped at token issuance time) or by the container's bridge IP for IMDSv1.