LocalStack and credentials#
LocalStack#
LocalStack serves SQS and SNS on one local port. The repository
ships a docker-compose.yaml that starts it:
services:
localstack:
image: localstack/localstack:4.14.0
environment:
SERVICES: sqs,sns
ports:
- "${LOCALSTACK_PORT:-4566}:4566"
healthcheck:
test: ["CMD", "curl", "-fsS", "http://localhost:4566/_localstack/health"]
interval: 2s
timeout: 2s
retries: 30
The justfile has the recipes you need:
| Recipe | What it does |
|---|---|
just localstack-up |
Starts LocalStack on port 4566 (set LOCALSTACK_PORT to change it) and waits until it is ready. |
just test-aws |
Runs the tests marked aws against LocalStack. |
just localstack-down |
Stops LocalStack. |
A service connects to it with endpoint_url. One URL serves both SQS and SNS. LocalStack accepts
any key pair, so the example passes AwsSecurity("test", "test"). A queue and a topic declared
with declare=True are created at startup, so LocalStack needs no setup:
import logging
from faststream import FastStream
from faststream_sqs_sns import AwsSecurity, CapoSqsBroker, SnsTopic, SqsQueue
broker = CapoSqsBroker(
region="us-east-1",
endpoint_url="http://localhost:4566",
# LocalStack accepts any key pair
security=AwsSecurity("test", "test"),
)
app = FastStream(broker)
logger = logging.getLogger(__name__)
@broker.subscriber(
SqsQueue("orders-billing", declare=True),
topic=SnsTopic("orders", declare=True),
)
async def bill(order: dict[str, int]) -> None:
logger.info("billing order %s", order["id"])
@app.after_startup
async def place_order() -> None:
await broker.publish({"id": 1}, SnsTopic("orders"))
just localstack-up
faststream run service:app
endpoint_url also points the broker at a VPC endpoint of AWS.
Credentials#
Without a security object the broker uses the credential chain of its backend: environment variables, the shared config, SSO, web identity, and the role of an ECS task or an EC2 instance.
AwsSecurity passes a static key pair, with a session token for temporary credentials.
from faststream_sqs_sns import AwsSecurity, CapoSqsBroker
def default_chain() -> CapoSqsBroker:
# environment, shared config, web identity, SSO, container or instance role
return CapoSqsBroker(region="eu-west-1")
def from_keys(
access_key_id: str, secret_access_key: str, session_token: str | None = None
) -> CapoSqsBroker:
security = AwsSecurity(access_key_id, secret_access_key, session_token)
return CapoSqsBroker(region="eu-west-1", security=security)
AwsSecurity keeps the secret and the token out of its repr, so they stay out of logs and
tracebacks.
Region#
region names the AWS region. When it is omitted, the backend reads AWS_REGION,
AWS_DEFAULT_REGION or the profile.