Skip to content

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

Replace all hard coded localhost with environment variable (#797)

Neriya Cohen15f874db392b
diff --git a/ministack/services/appsync_events.py b/ministack/services/appsync_events.py
index 438bc01e..c6cd3b7b 100644
--- a/ministack/services/appsync_events.py
+++ b/ministack/services/appsync_events.py
@@ -38,6 +38,8 @@ from ministack.core.responses import (
logger = logging.getLogger("appsync_events")
+_MINISTACK_HOST = os.environ.get("MINISTACK_HOST", "localhost")
+
# ---------------------------------------------------------------------------
# In-memory state
# ---------------------------------------------------------------------------
@@ -133,7 +135,7 @@ def _default_dns_for_api(api_id: str) -> dict[str, str]:
"""
region = get_region()
port = os.environ.get("GATEWAY_PORT") or os.environ.get("EDGE_PORT") or "4566"
- mini_host = os.environ.get("MINISTACK_HOST", "localhost")
+ mini_host = _MINISTACK_HOST
host_t = os.environ.get("APPSYNC_EVENTS_HTTP_HOST_TEMPLATE", "").strip()
rt_t = os.environ.get("APPSYNC_EVENTS_REALTIME_HOST_TEMPLATE", "").strip()
if host_t and rt_t:
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index f7e05a74..badc9064 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -54,6 +54,7 @@ logger = logging.getLogger("cloudformation")
# Module-level REGION kept for legacy imports; new code must use get_region()
# so AWS::Region / ARNs reflect the caller's request region (#398).
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
+_MINISTACK_HOST = os.environ.get("MINISTACK_HOST", "localhost")
def _physical_name(stack_name: str, logical_id: str, *,
@@ -3259,7 +3260,7 @@ def _apigw_v2_api_create(logical_id, props, stack_name):
"apiId": api_id,
"name": name,
"protocolType": protocol,
- "apiEndpoint": f"http://{api_id}.execute-api.{os.environ.get('MINISTACK_HOST', 'localhost')}:{os.environ.get('GATEWAY_PORT', '4566')}",
+ "apiEndpoint": f"http://{api_id}.execute-api.{_MINISTACK_HOST}:{os.environ.get('GATEWAY_PORT', '4566')}",
"createdDate": now_iso(),
"routeSelectionExpression": props.get("RouteSelectionExpression", "$request.method $request.path"),
"apiKeySelectionExpression": props.get("ApiKeySelectionExpression", "$request.header.x-api-key"),
diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.py
index a0c33787..d7547a40 100644
--- a/ministack/services/dynamodb.py
+++ b/ministack/services/dynamodb.py
@@ -37,6 +37,8 @@ from ministack.services._dynamodb_keywords import AWS_KEYWORDS
logger = logging.getLogger("dynamodb")
+_MINISTACK_HOST = os.environ.get("MINISTACK_HOST", "localhost")
+
def _conditional_check_failed(data, old_item, message="The conditional request failed"):
"""Standard ConditionalCheckFailedException response, with `Item` populated
@@ -3089,10 +3091,9 @@ def _describe_endpoints(data):
# Address for follow-up calls. Returning real-AWS hostname would redirect
# SDKs AWAY from MiniStack on cache miss. Return MiniStack's own host so
# endpoint-discovery-aware SDKs keep talking to us.
- host = os.environ.get("MINISTACK_HOST", "localhost")
port = os.environ.get("GATEWAY_PORT", "4566")
return json_response({
- "Endpoints": [{"Address": f"{host}:{port}", "CachePeriodInMinutes": 1440}]
+ "Endpoints": [{"Address": f"{_MINISTACK_HOST}:{port}", "CachePeriodInMinutes": 1440}]
})
diff --git a/ministack/services/ecs.py b/ministack/services/ecs.py
index e3daa113..0a115378 100644
--- a/ministack/services/ecs.py
+++ b/ministack/services/ecs.py
@@ -46,6 +46,8 @@ from ministack.services import ecs_metadata
logger = logging.getLogger("ecs")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
+_MINISTACK_HOST = os.environ.get("MINISTACK_HOST", "localhost")
+_GATEWAY_PORT = os.environ.get("GATEWAY_PORT", "4566")
_clusters = AccountScopedDict()
_task_defs = AccountScopedDict()
@@ -1737,7 +1739,8 @@ def _submit_attachment_state_changes(data):
def _discover_poll_endpoint(data):
- return json_response({"endpoint": "http://localhost:4566", "telemetryEndpoint": "http://localhost:4566"})
+ endpoint = f"http://{_MINISTACK_HOST}:{_GATEWAY_PORT}"
+ return json_response({"endpoint": endpoint, "telemetryEndpoint": endpoint})
# ---------------------------------------------------------------------------
diff --git a/ministack/services/eks.py b/ministack/services/eks.py
index 6e02b0ef..3bab25cb 100644
--- a/ministack/services/eks.py
+++ b/ministack/services/eks.py
@@ -36,6 +36,7 @@ from ministack.core.responses import (
logger = logging.getLogger("eks")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
+_MINISTACK_HOST = os.environ.get("MINISTACK_HOST", "localhost")
EKS_K3S_IMAGE = os.environ.get("EKS_K3S_IMAGE", "rancher/k3s:v1.31.4-k3s1")
EKS_BASE_PORT = int(os.environ.get("EKS_BASE_PORT", "16443"))
DOCKER_NETWORK = os.environ.get("DOCKER_NETWORK", "")
@@ -65,9 +66,8 @@ _oidc_keypair = None # (private_key, jwk_dict, kid)
def _ministack_issuer_base():
- host = os.environ.get("MINISTACK_HOST", "localhost")
port = os.environ.get("GATEWAY_PORT", "4566")
- return f"http://{host}:{port}/oidc"
+ return f"http://{_MINISTACK_HOST}:{port}/oidc"
def _new_oidc_id():
diff --git a/ministack/services/elasticache.py b/ministack/services/elasticache.py
index e134b890..a6e172a0 100644
--- a/ministack/services/elasticache.py
+++ b/ministack/services/elasticache.py
@@ -32,6 +32,7 @@ from ministack.core.responses import AccountScopedDict, apply_image_prefix, get_
logger = logging.getLogger("elasticache")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
+_MINISTACK_HOST = os.environ.get("MINISTACK_HOST", "localhost")
REDIS_DEFAULT_HOST = os.environ.get("REDIS_HOST", "redis")
REDIS_DEFAULT_PORT = int(os.environ.get("REDIS_PORT", "6379"))
BASE_PORT = int(os.environ.get("ELASTICACHE_BASE_PORT", "16379"))
@@ -159,7 +160,7 @@ def _spawn_redis_container(name, engine, engine_version, labels):
host_port = _port_counter[0]
_port_counter[0] += 1
- endpoint_host = "localhost"
+ endpoint_host = _MINISTACK_HOST
endpoint_port = host_port
if engine == "redis":
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index 6ec69ba4..8149e5c2 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -63,6 +63,8 @@ from ministack.core.responses import (
logger = logging.getLogger("lambda")
+_MINISTACK_HOST = os.environ.get("MINISTACK_HOST", "localhost")
+
def _emit_lambda_metrics(function_name: str, duration_ms: float,
error: bool, throttle: bool) -> None:
@@ -1196,7 +1198,7 @@ def _presigned_code_url(func_name: str) -> str:
ministack endpoint and dress the URL up with the query params SDKs and
scripts expect, so `pip-style` pull-and-extract code works unchanged.
"""
- host = os.environ.get("MINISTACK_HOST", "localhost")
+ host = _MINISTACK_HOST
port = os.environ.get("GATEWAY_PORT", os.environ.get("EDGE_PORT", "4566"))
qs = (
f"?X-Amz-Algorithm=AWS4-HMAC-SHA256"
@@ -3333,7 +3335,7 @@ def _execute_function_local(func: dict, event: dict) -> dict:
# Subprocess runs on the same host as ministack — point it at
# ourselves so boto3 calls land back here, not at real AWS.
gateway_port = os.environ.get("GATEWAY_PORT", "4566")
- endpoint = f"http://localhost:{gateway_port}"
+ endpoint = f"http://{_MINISTACK_HOST}:{gateway_port}"
if endpoint:
env["AWS_ENDPOINT_URL"] = endpoint
env.update(env_vars)
@@ -3814,9 +3816,8 @@ def _untag_resource(resource_arn: str, query_params: dict):
def _layer_content_url(layer_name: str, version: int) -> str:
- host = os.environ.get("MINISTACK_HOST", "localhost")
port = os.environ.get("GATEWAY_PORT", "4566")
- return f"http://{host}:{port}/_ministack/lambda-layers/{layer_name}/{version}/content"
+ return f"http://{_MINISTACK_HOST}:{port}/_ministack/lambda-layers/{layer_name}/{version}/content"
def _publish_layer_version(layer_name: str, data: dict):
diff --git a/ministack/services/opensearch.py b/ministack/services/opensearch.py
index 5fb54145..ee9a5f4f 100644
--- a/ministack/services/opensearch.py
+++ b/ministack/services/opensearch.py
@@ -36,6 +36,8 @@ from ministack.core.responses import (
logger = logging.getLogger("opensearch")
+_MINISTACK_HOST = os.environ.get("MINISTACK_HOST", "localhost")
+
# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
@@ -242,7 +244,7 @@ def _spawn_dataplane(domain_name: str, engine_version: str):
run_kwargs["network"] = DOCKER_NETWORK
cid = None
- endpoint_host, endpoint_port = "localhost", host_port
+ endpoint_host, endpoint_port = _MINISTACK_HOST, host_port
try:
container = docker.containers.run(**run_kwargs)
cid = container.id
@@ -279,7 +281,7 @@ def _spawn_dataplane(domain_name: str, engine_version: str):
dash_kwargs["network"] = DOCKER_NETWORK
dash_container = docker.containers.run(**dash_kwargs)
dash_cid = dash_container.id
- dash_endpoint = f"localhost:{dash_host_port}"
+ dash_endpoint = f"{_MINISTACK_HOST}:{dash_host_port}"
logger.info(
"OpenSearch Dashboards: started %s on port %s",
domain_name, dash_host_port,
diff --git a/ministack/services/rds.py b/ministack/services/rds.py
index b3548efa..e4dedd8e 100644
--- a/ministack/services/rds.py
+++ b/ministack/services/rds.py
@@ -48,6 +48,7 @@ from ministack.core.responses import AccountScopedDict, apply_image_prefix, get_
logger = logging.getLogger("rds")
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
+_MINISTACK_HOST = os.environ.get("MINISTACK_HOST", "localhost")
BASE_PORT = int(os.environ.get("RDS_BASE_PORT", "15432"))
RDS_TMPFS_SIZE = os.environ.get("RDS_TMPFS_SIZE", "256m")
RDS_PERSIST = os.environ.get("RDS_PERSIST", "0").lower() in ("1", "true", "yes")
@@ -680,7 +681,7 @@ def _create_db_instance(p):
arn = f"arn:aws:rds:{get_region()}:{get_account_id()}:db:{db_id}"
dbi_resource_id = f"db-{new_uuid().replace('-', '')[:20].upper()}"
- endpoint_host = "localhost"
+ endpoint_host = _MINISTACK_HOST
endpoint_port = port
host_port = None
docker_container_id = None
@@ -1178,7 +1179,7 @@ def _create_read_replica(p):
"InstanceCreateTime": _format_time(time.time()),
"ReadReplicaDBInstanceIdentifiers": [],
"Endpoint": {
- "Address": "localhost",
+ "Address": _MINISTACK_HOST,
"Port": _next_port(),
"HostedZoneId": "Z2R2ITUGPM61AM",
},
@@ -1222,7 +1223,7 @@ def _restore_from_snapshot(p):
"MasterUsername": snap.get("MasterUsername", "admin"),
"DBName": snap.get("DBName", ""),
"Endpoint": {
- "Address": "localhost",
+ "Address": _MINISTACK_HOST,
"Port": _next_port(),
"HostedZoneId": "Z2R2ITUGPM61AM",
},
diff --git a/ministack/services/s3tables.py b/ministack/services/s3tables.py
index fb82dbb4..b0ec7c91 100644
--- a/ministack/services/s3tables.py
+++ b/ministack/services/s3tables.py
@@ -47,6 +47,9 @@ from ministack.core.responses import (
logger = logging.getLogger("s3tables")
+_MINISTACK_HOST = os.environ.get("MINISTACK_HOST", "localhost")
+_GATEWAY_PORT = os.environ.get("GATEWAY_PORT", "4566")
+
# ── In-memory state ────────────────────────────────────────
_table_buckets = AccountScopedDict()
@@ -345,7 +348,7 @@ def _iceberg_load_table(namespace, table_name):
"metadata": table.get("_iceberg_metadata", {}),
"config": {
"s3.access-key-id": "test", "s3.secret-access-key": "test",
- "s3.endpoint": "http://localhost:4566", "s3.path-style-access": "true",
+ "s3.endpoint": f"http://{_MINISTACK_HOST}:{_GATEWAY_PORT}", "s3.path-style-access": "true",
},
})
return error_response_json("NotFoundException", f"Table {namespace}.{table_name} not found", 404)
diff --git a/tests/bench_recording.py b/tests/bench_recording.py
index 4e5e6b05..eb6836ab 100644
--- a/tests/bench_recording.py
+++ b/tests/bench_recording.py
@@ -20,6 +20,7 @@ Options:
"""
import argparse
+import os
import statistics
import time
import uuid
@@ -27,7 +28,7 @@ import uuid
import boto3
import requests
-ENDPOINT = "http://localhost:4566"
+ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
REGION = "us-east-1"
diff --git a/tests/test_account.py b/tests/test_account.py
index e9f757e8..a5ddbea3 100644
--- a/tests/test_account.py
+++ b/tests/test_account.py
@@ -1,14 +1,17 @@
import json
+import os
import urllib.request
import pytest
import boto3
+_ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
+
@pytest.fixture(scope="module")
def acct():
- return boto3.client("account", endpoint_url="http://localhost:4566",
+ return boto3.client("account", endpoint_url=_ENDPOINT,
region_name="us-east-1",
aws_access_key_id="test", aws_secret_access_key="test")
@@ -24,7 +27,7 @@ def test_account_get_account_information_includes_account_state_field():
"""AccountState added 2026-04-29; verify present on the wire even though
older botocore may strip it."""
req = urllib.request.Request(
- "http://localhost:4566/getAccountInformation",
+ f"{_ENDPOINT}/getAccountInformation",
data=b"{}",
headers={
"Content-Type": "application/json",