Skip to content

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

feat(ec2): opt-in launch options for instance containers (EC2_DOCKER_FLAGS) (#1489)

iot-rocket71f52c967b97
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e030a06b..36e204d5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
+### Added
+- **EC2 — opt-in launch options for instance containers (`EC2_DOCKER_FLAGS`)** — a registered image that boots an operating system (systemd as PID 1) needs container options the fixed launch arguments cannot express: unprivileged, `unshare` fails with `Operation not permitted` and the instance terminates at boot. `EC2_DOCKER_FLAGS` now takes a docker-CLI-style string (`--privileged`, `--cap-add`, `-e`, `-v`, `--tmpfs`, `--add-host`, `-m`, `--shm-size`) applied to every instance container; unset, nothing changes. `--init` is refused — instance containers always run with init. Contributed by @iot-rocket.
### Fixed
- **IoT Core — an unresolvable action role fails `CreateTopicRule` instead of silently dropping the rule (`AUTH=true`)** — the role check added with the IAM request authorization answered `200 {}` while storing nothing: the store-layer helper returned the error response as a value and both API handlers discarded it, so a client (or a CloudFormation stack) saw success minus its rule. The check now raises through the same door as invalid rule SQL, `CreateTopicRule` / `ReplaceTopicRule` answer `400 InvalidRequestException` (`Unable to assume role: {arn}`) as real IoT does when it cannot assume the role, and the CloudFormation provisioner fails the resource. With `AUTH=false` nothing changes. Reported by @iot-rocket.
- **RDS — Aurora PostgreSQL major-version selectors return the matching catalog** — `DescribeDBEngineVersions` treated `EngineVersion=16` as an exact version and returned nothing. Major-only selectors now return every advertised minor in that family, and `DefaultOnly=true` narrows the result to AWS's configured default minor for that major.
diff --git a/ministack/services/ec2.py b/ministack/services/ec2.py
index 6264cb6e..b3590acd 100644
--- a/ministack/services/ec2.py
+++ b/ministack/services/ec2.py
@@ -87,6 +87,9 @@ logger = logging.getLogger("ec2")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
DOCKER_NETWORK = os.environ.get("DOCKER_NETWORK", "")
+# docker-CLI-style flags applied to every instance container (e.g. --privileged
+# for a systemd guest). Parsed by _parse_ec2_docker_flags; --init is refused.
+EC2_DOCKER_FLAGS = os.environ.get("EC2_DOCKER_FLAGS", "")
# Docker client, created on first use. Only registered images reach for it, so
# an emulator nobody registered an AMI with never imports docker-py at all.
@@ -2111,6 +2114,75 @@ def _image_has_entrypoint(client, ref):
return bool((image.attrs.get("Config") or {}).get("Entrypoint"))
+def _parse_ec2_docker_flags(flags: str) -> dict:
+ """Translate a docker-CLI-style ``EC2_DOCKER_FLAGS`` string into docker-py
+ ``containers.run()`` kwargs (subset; unknown flags are ignored, malformed
+ input is warned about and ignored rather than failing the launch).
+ ``--init`` is refused: init reaps whatever PID 1 leaves behind, and an image
+ with no ENTRYPOINT relies on it to reap the appended keepalive command —
+ disabling it silently breaks the box. Same approach as
+ ``_parse_docker_flags`` (``LAMBDA_DOCKER_FLAGS``) in ``lambda_svc.py``,
+ kept service-local like everything else in this file."""
+ if not flags:
+ return {}
+ import argparse
+ import shlex
+
+ try:
+ tokens = shlex.split(flags)
+ except ValueError as e:
+ logger.warning("EC2: could not parse EC2_DOCKER_FLAGS %r: %s", flags, e)
+ return {}
+ kept = []
+ for tok in tokens:
+ if tok == "--init" or tok.startswith("--init="):
+ logger.warning("EC2: ignoring %s in EC2_DOCKER_FLAGS — "
+ "instance containers always run with init", tok)
+ continue
+ kept.append(tok)
+
+ class _QuietParser(argparse.ArgumentParser):
+ # argparse's default error() prints usage and calls sys.exit(), which
+ # must never happen inside the server — raise instead and warn below.
+ def error(self, message):
+ raise ValueError(message)
+
+ parser = _QuietParser(add_help=False)
+ parser.add_argument("-e", "--env", action="append", default=[])
+ parser.add_argument("-v", "--volume", action="append", default=[])
+ parser.add_argument("--cap-add", action="append", default=[])
+ parser.add_argument("--tmpfs", action="append", default=[])
+ parser.add_argument("--add-host", action="append", default=[])
+ parser.add_argument("-m", "--memory")
+ parser.add_argument("--shm-size")
+ parser.add_argument("--privileged", action="store_true")
+ try:
+ args, unknown = parser.parse_known_args(kept)
+ except ValueError as e:
+ logger.warning("EC2: could not parse EC2_DOCKER_FLAGS %r: %s", flags, e)
+ return {}
+ if unknown:
+ logger.debug("EC2: ignoring unsupported EC2_DOCKER_FLAGS tokens: %s", unknown)
+ kwargs = {}
+ if args.privileged:
+ kwargs["privileged"] = True
+ if args.env:
+ kwargs["environment"] = dict(e.partition("=")[::2] for e in args.env)
+ if args.volume:
+ kwargs["volumes"] = args.volume
+ if args.cap_add:
+ kwargs["cap_add"] = args.cap_add
+ if args.tmpfs:
+ kwargs["tmpfs"] = {path: opts for path, _, opts in (t.partition(":") for t in args.tmpfs)}
+ if args.add_host:
+ kwargs["extra_hosts"] = {h: ip for h, _, ip in (a.partition(":") for a in args.add_host)}
+ if args.memory:
+ kwargs["mem_limit"] = args.memory
+ if args.shm_size:
+ kwargs["shm_size"] = args.shm_size
+ return kwargs
+
+
def _vm_launch(inst, image_ref):
"""Boot one instance record as a container. Raises on create/start failure;
the caller backs the records out and surfaces the error."""
@@ -2144,6 +2216,7 @@ def _vm_launch(inst, image_ref):
kwargs["command"] = ["sleep", "infinity"]
if network:
kwargs["network"] = network
+ kwargs.update(_parse_ec2_docker_flags(EC2_DOCKER_FLAGS))
container = client.containers.run(ref, **kwargs)
global _docker_in_use
_docker_in_use = True
diff --git a/tests/test_ec2.py b/tests/test_ec2.py
index 4110dfb9..07d2ecdb 100644
--- a/tests/test_ec2.py
+++ b/tests/test_ec2.py
@@ -3855,6 +3855,41 @@ def test_ec2_registered_ami_boots_a_container(vm):
assert inst["PrivateDnsName"] == "ip-172-30-0-9.ec2.internal"
+def test_ec2_parse_docker_flags():
+ kwargs = ec2mod._parse_ec2_docker_flags(
+ "--privileged -e A=1 --env B=two -v /h:/c:ro --cap-add SYS_ADMIN "
+ "--tmpfs /run:rw,size=64m --add-host me:10.0.0.1 -m 512m --shm-size 128m "
+ "--init=false --bogus-flag xyz")
+ assert kwargs["privileged"] is True
+ assert kwargs["environment"] == {"A": "1", "B": "two"}
+ assert kwargs["volumes"] == ["/h:/c:ro"]
+ assert kwargs["cap_add"] == ["SYS_ADMIN"]
+ assert kwargs["tmpfs"] == {"/run": "rw,size=64m"}
+ assert kwargs["extra_hosts"] == {"me": "10.0.0.1"}
+ assert kwargs["mem_limit"] == "512m"
+ assert kwargs["shm_size"] == "128m"
+ # --init is refused, never forwarded: instance containers always run with init.
+ assert "init" not in kwargs
+ assert ec2mod._parse_ec2_docker_flags("") == {}
+ # Malformed input is ignored rather than raising or exiting inside the server:
+ # a flag missing its value trips argparse's error path, an unbalanced quote
+ # trips shlex.
+ for bad in ("-m", "--cap-add", "'unbalanced"):
+ assert ec2mod._parse_ec2_docker_flags(bad) == {}
+
+
+def test_ec2_docker_flags_reach_the_container(vm, monkeypatch):
+ fake, created = vm
+ monkeypatch.setattr(ec2mod, "EC2_DOCKER_FLAGS", "--privileged --cap-add SYS_ADMIN")
+ ami = _register("example/box:1")
+ iids, _ = _launch(ami)
+ created.extend(iids)
+ run = fake._runs[0]
+ assert run["privileged"] is True
+ assert run["cap_add"] == ["SYS_ADMIN"]
+ assert run["init"] is True
+
+
def test_ec2_failed_boot_backs_every_record_out(monkeypatch):
fake = _fake_docker(run_error=RuntimeError("no such image"))
monkeypatch.setattr(ec2mod, "_get_docker", lambda: fake)