跳到正文
DEV Community· iAmSherif 💎·· 1 小時前AI 評分64

如何使用 AWS Emulator 在本機測試 AWS Lambda

How to Test AWS Lambda Locally Using AWS Emulator

AI 導讀

作者以 AWS Emulator 和 Docker 示範在本機測試 AWS Lambda,並串接 API Gateway、Lambda 與 DynamoDB 的 notes API。

正文

Over the years building on AWS, one of my biggest challenges has been local testing. It takes a lot of hard work to get right. Until now, if you have built anything on Lambda, you know the loop: change one line, deploy, wait, test, open CloudWatch, repeat. On November 11, 2026, AWS released AWS Emulator, a free, open-source emulator of the AWS APIs that runs on your own machine. It takes the deploy out of that loop. Your AWS CLI and SDK calls go to a local endpoint instead of AWS, and the answers come back in milliseconds.

In this article, I will walk you through testing an API Gateway → Lambda → DynamoDB app locally with AWS Emulator and Docker, step by step. More importantly, I will show you every error I hit on both runtimes and how I worked around it. The emulator is not AWS, and the gaps are where your time goes.

Note: Everything here was tested on an Intel Mac with Docker, on AWS Emulator 1.0.348 to 1.0.505. Behaviour changed between those versions, so check yours before you trust any finding here.

What is AWS Emulator?

AWS Emulator is a single local program that serves AWS API endpoints. It has no console and no UI. You start it, point your AWS CLI or SDK at it with a few environment variables, and run your code as usual. No AWS account, no credentials, no bill.

A few things make it different from the tools you may already know:

  • It is generated from AWS's own API models.
  • It is built and maintained by AI agents.
  • It runs natively on Linux only. On macOS and Windows you run it in Docker, from an image you build yourself. AWS does not publish one.
  • Everything lives in memory. Stop the emulator and your tables, functions and APIs are gone.

What it is not

This part matters more than the feature list:

  • Don't rely on its IAM. On 1.0.348 and 1.0.367, a function ran with a role that didn't exist. On 1.0.505, a role with no DynamoDB policy was denied. Enforcement is partial and changes between versions.
  • It is one account (000000000000) and one Region. No cross-account or cross-Region behaviour.
  • Lambda runs only Zip-packaged Python and Node.js functions. No container images and no other runtimes yet, such as Java or Go. Functions on other runtimes deploy without error, then fail when invoked. If your Lambda is a Docker image, the emulator will store it but won't run it.
  • It is not for security testing or production.

So in this article, Docker runs the emulator, not your Lambda. The usual AWS Lambda base image approach does not apply here.

What I Built

A small notes** API** with three routes:

  • POST /notes creates a note and returns 201
  • GET /notes/{id} returns one note, or 404
  • GET /notes lists all notes

It's an AWS CDK app I newly built for this article: an API Gateway HTTP API with one Lambda function per route (three Node.js 22 functions), reading and writing one DynamoDB table, Notes, keyed on id.

API Gateway → Lambda → DynamoDB, all inside the emulator

Everything except the client runs inside the emulator.

Prerequisites

  • Docker, running, with about 2 GB of memory free for the emulator and about 2 GB of disk for its image.
  • AWS CLI v2. The AWS CDK CLI too, since Step 4 deploys with it.
  • Node.js 22, to match the nodejs22.x functions in the CDK app, and Python 3.12 if you run the Python probe in Step 3. Match the Lambda runtime you will deploy to, not your system default. My machine had Python 3.14; uv python install 3.12 fixed that.
  • No AWS account. You won't need one.

Step 1 - Build and Run the Emulator in Docker

AWS does not publish an image, so you build one from the Dockerfile in the User Guide. Create emulator/Dockerfile:

FROM public.ecr.aws/amazonlinux/amazonlinux:2023-minimal
ADD https://downloads.aws.com/aws-emulator/packages/aws-emulator/LTS/latest/aws-emulator-x86_64.rpm /tmp/aws-emulator.rpm
RUN rpm -i /tmp/aws-emulator.rpm && rm /tmp/aws-emulator.rpm \
    && mkdir -p /home/emulator && chown 1000 /home/emulator
USER 1000
ENV HOME=/home/emulator
EXPOSE 9297
ENTRYPOINT ["aws-emulator", "-b", "0.0.0.0"]

On Apple silicon, replace aws-emulator-x86_64.rpm with aws-emulator-aarch64.rpm. I only ran the x86_64 image, so I can't vouch for the Arm one.

Build it, then start the emulator:

docker build -t aws-emulator emulator/

mkdir -p ~/.aws/emulator
docker run -d --rm --name aws-emulator --memory=2g --memory-swap=2g \
  -p 127.0.0.1:9297:9297 \
  -e HOME="$HOME" -v "$HOME/.aws/emulator:$HOME/.aws/emulator" \
  aws-emulator -p 9297 --telemetry off

What matters in that command:

  • mkdir first. On Linux, if Docker creates the folder, root owns it and your SDK can't read it. Also add --user "$(id -u):$(id -g)" on Linux.
  • -p 127.0.0.1:9297:9297, never -p 9297:9297. The short form opens the emulator to your whole network.
  • The volume mount is how the emulator hands you its credentials, config and certificate. It writes them to ~/.aws/emulator/9297/.
  • --telemetry off, because the emulator sends usage data to AWS by default. AWS says it only looks at that data in aggregate and keeps it from being tied to users or accounts, but it's your choice. You can also set EMULATOR_TELEMETRY=off instead of passing the flag.
  • --memory=2g. Go over it and the container dies with exit code 137, taking your resources with it.

Wait until it is healthy (about 3 s in my runs):

curl -sf --cacert ~/.aws/emulator/9297/ca.pem https://127.0.0.1:9297/__admin/health

You should get back ok. In zsh you'll see ok%.

Two warnings you can ignore. docker logs aws-emulator shows a warning that the emulator listens on 0.0.0.0. That's the -b 0.0.0.0 in the Dockerfile, which a container needs, and the 127.0.0.1: in the port mapping still keeps it on your machine. The image build also prints NOKEY for the RPM signature, because the base image doesn't have AWS's signing key. The package installs fine, but its signature isn't checked, so import AWS's key first if that matters to you.

Step 2 - Point the AWS CLI and SDKs at the Emulator

Open a second terminal. Create scripts/env-emulator.sh and source it before every CLI, SDK or test call:

unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN AWS_PROFILE
E=~/.aws/emulator/9297
export AWS_ENDPOINT_URL=https://127.0.0.1:9297
export AWS_SHARED_CREDENTIALS_FILE=$E/emulator_credentials
export AWS_CONFIG_FILE=$E/config
export AWS_CA_BUNDLE=$E/ca.pem
export NODE_EXTRA_CA_CERTS=$E/ca.pem   # Node.js SDK only
export AWS_EC2_METADATA_DISABLED=true
export AWS_DISABLE_HOST_PREFIX_INJECTION=true
export AWS_REGION=us-east-1 AWS_DEFAULT_REGION=us-east-1

Three rules worth knowing up front:

  1. Use 127.0.0.1, never localhost. localhost can resolve to ::1, and some SDKs then put the S3 bucket name in the host name, which the emulator rejects.
  2. The Node.js SDK needs NODE_EXTRA_CA_CERTS. Node reads it once, at start-up. A --watch test runner or a REPL that was already running keeps trusting the old certificate after an emulator restart. Restart that process too.
  3. Every restart resets everything: tables, functions, APIs, credentials and the CA certificate. Always go: start emulator → source env → deploy.

Check it works:

aws sts get-caller-identity

You should see account 000000000000.

Add a safety guard

The whole point is to never touch real AWS by accident, say from a shell where you forgot to source the env file. So every deploy and test script starts with a guard:

[ "$AWS_ENDPOINT_URL" = "https://127.0.0.1:9297" ] || { echo "Not the emulator. Abort."; exit 1; }
ACCOUNT=$(aws sts get-caller-identity --query Account --output text)
[ "$ACCOUNT" = "000000000000" ] || { echo "Wrong account: $ACCOUNT"; exit 1; }

The endpoint check runs before any network call. I tested it by pointing at dynamodb.us-east-1.amazonaws.com: it aborted with no request sent. I also repeated the same check inside my integration test setup, so running pytest or node --test by hand in the wrong shell can't reach AWS either. You will see in Step 3 why I didn't want to trust my eyes alone.

Step 3 (Optional) - Check What Your Lambda Sees Inside the Emulator

Before you deploy your real function, deploy a throwaway Lambda whose only job is to report what it sees: the runtime version, the environment variables, which services it can reach and the event it receives. Most of the gaps in the errors section below show up here, and the emulator changes often, so this is how you check them on your own version.

Here is the Python version. The important part is that every check is wrapped on its own, so one surprise doesn't hide the rest:

import json, os, sys

def check(out, name, fn):
    try:
        out[name] = fn()
    except Exception as e:
        out[name] = f"{type(e).__name__}: {e}"

def handler(event, context):
    import boto3
    out = {}
    check(out, "python", lambda: sys.version)
    check(out, "aws_env", lambda: sorted(k for k in os.environ if k.startswith("AWS_")))
    check(out, "tables", lambda: boto3.client("dynamodb").list_tables()["TableNames"])
    check(out, "endpoint", lambda: boto3.client("dynamodb").meta.endpoint_url)
    check(out, "event", lambda: event)
    return {"statusCode": 200, "body": json.dumps(out, default=str)}

The Node.js probe does the same with process.version, process.env and await import(name) for a list of core modules. One tip: build the module name as a variable (const m = '@aws-sdk/client-dynamodb'; await import(m)), otherwise esbuild tries to bundle it.

Deploy it, invoke it and read the output:

zip probe.zip probe.py
aws lambda create-function --function-name probe --runtime python3.12 \
  --handler probe.handler --zip-file fileb://probe.zip \
  --role arn:aws:iam::000000000000:role/lambda-role
aws lambda wait function-active-v2 --function-name probe
aws lambda invoke --function-name probe /dev/stdout

The role doesn't exist. On 1.0.348 and 1.0.367 that didn't matter. On 1.0.505, a role with no DynamoDB policy was denied access, so if you get AccessDeniedException, create a real role with the permissions the function needs.

For an API Gateway → Lambda → DynamoDB app, the answer that matters most is this one:

  • Can the function's SDK reach DynamoDB? Yes, with no endpoint and no credentials in the function code. Inside the function there is no AWS_ACCESS_KEY_ID, no secret, no session token and no AWS_ENDPOINT_URL. The SDK inside the emulator is a shim that routes calls internally.

It also gave me a scare. In Python, client.meta.endpoint_url reported https://dynamodb.us-east-1.amazonaws.com, the real AWS hostname. For a project whose first rule is "never call real AWS", that looks alarming. Here is how I confirmed it was safe:

  • list_tables() returned a table that only existed in the emulator.
  • A DNS lookup inside the function failed with: a Lambda function in this emulator has no host network to reach.
  • The emulator's own log recorded the calls.

So the function has no network at all. The reported endpoint is simply misleading, and that is exactly why the safety guard from Step 2 checks the account id instead of trusting what the code reports.

Step 4 - Deploy Your App to the Emulator

If your app is already in AWS CDK, you don't need new deploy scripts. cdk deploy works against the emulator as it is. I tested it with the notes app from What I Built: an HTTP API, three nodejs22.x functions and a DynamoDB table. Bootstrap, asset upload, deploy, hotswap, cdk watch and destroy all worked. One route needed a local-only fix (Error #7).

Deploy With AWS CDK

With the env file sourced and the safety guard passing:

export CDK_DISABLE_CLI_TELEMETRY=true
cdk bootstrap aws://000000000000/us-east-1
cdk deploy --require-approval never

Why it works without changes:

  • The CDK CLI reads AWS_ENDPOINT_URL, and the variable takes priority over the endpoint in the emulator's config file.
  • It trusts the emulator's certificate through either AWS_CA_BUNDLE or NODE_EXTRA_CA_CERTS. With neither set, bootstrap fails with self-signed certificate.
  • NodejsFunction left the AWS SDK out of the bundle, because my stack sets externalModules: ['@aws-sdk/*']. Keep it that way: a bundled SDK won't load in the emulator.

Don't trust CREATE_COMPLETE alone. Check the resources with the CLI, and call every route: one of mine deployed cleanly and still failed (Error #7). To check a function's state, use aws lambda get-function-configuration; list-functions returned None for State.

The HTTP API invoke URL has no stage in the path when you use the $default stage:

https://127.0.0.1:9297/_aws/execute-api/{apiId}/notes

.../{apiId}/$default/notes works too. aws apigatewayv2 get-apis prints the endpoint for you.

Keep production unchanged. Put any local-only change behind a context flag, deploy with cdk deploy -c local=true, and check that cdk synth without the flag gives exactly the same template as before.

Clean up with cdk destroy. A table with RemovalPolicy.RETAIN stays behind, as it would on AWS. Restarting the emulator clears everything.

Step 5 - Test It

With everything deployed, you can test the whole path, API Gateway → Lambda → DynamoDB, without leaving your machine. There are three checks worth knowing.

Call the API

Use the invoke URL from Step 4. If you don't have it, list the APIs in the emulator. The ApiEndpoint of each one is its base URL, for example https://127.0.0.1:9297/_aws/execute-api/:

aws apigatewayv2 get-apis

Then create a note and read it back with the id from the response:

API_URL=https://127.0.0.1:9297/_aws/execute-api/<apiId>
CA=~/.aws/emulator/9297/ca.pem
curl -s --cacert $CA -X POST "$API_URL/notes" \
  -H 'content-type: application/json' -d '{"title":"First note"}'
curl -s --cacert $CA "$API_URL/notes/<id>"
curl -s --cacert $CA "$API_URL/notes"

Also test the unhappy paths: a bad body should return 400, an unknown id 404.

Invoke the Lambda directly

First, create an event.json that looks like what API Gateway sends. If you ran the probe in Step 3, use the event it captured. Otherwise, write a minimal one. This is an HTTP API (payload 2.0) event for GET /notes/{id}:

cat > event.json <<'EOF'
{
  "version": "2.0",
  "routeKey": "GET /notes/{id}",
  "rawPath": "/notes/123",
  "rawQueryString": "",
  "headers": { "content-type": "application/json" },
  "pathParameters": { "id": "123" },
  "requestContext": {
    "http": { "method": "GET", "path": "/notes/123" },
    "routeKey": "GET /notes/{id}",
    "stage": "$default"
  },
  "isBase64Encoded": false
}
EOF

A REST API event has a different shape: httpMethod, resource, path and pathParameters at the top level. If your handler reads other fields, add them too.

Then invoke the function without going through API Gateway. CDK generates function names, so look yours up first:

aws lambda list-functions --query 'Functions[].FunctionName'
aws lambda invoke --function-name <your-function> --cli-binary-format raw-in-base64-out \
  --payload file://event.json /dev/stdout

This is how you reach the cases API Gateway blocks before your function runs, like an undefined route. It is also your fallback if a future emulator version breaks the HTTP path.

Check what landed in DynamoDB

After a POST /notes, the new item should be in the table. CDK generates the table name, so list the tables first:

aws dynamodb list-tables
aws dynamodb scan --table-name <your-table>

Errors I Hit and How I Fixed Them

Most of these trace back to one fact: the Lambda runtimes inside AWS Emulator are not the real interpreters, and the AWS SDK inside them is a shim.

Python runtime

Finding: python3.12 is not CPython 3.12

Inside the function, sys.version returned:

3.14.0.alpha ... [RustPython 0.6.0 with rustc 1.99.1]

That's RustPython, a Python interpreter written in Rust, not CPython. This cuts both ways. Code that uses 3.13 or 3.14 features can pass in the emulator and fail on real Lambda. Code that relies on CPython behaviour or C extensions can fail in the emulator and work on AWS.

Workaround: run your unit tests on a real CPython 3.12. The emulator proves the wiring, not the interpreter.

Error #1: boto3 has no version

AttributeError: module 'boto3' has no attribute '__version__'

The boto3 inside the function is a stand-in, not the real library. Workaround: use getattr(boto3, "__version__", "?"), and watch for libraries that read boto3's version.

Error #2: Credentials with no access key

TypeError: 'NoneType' object is not subscriptable

Unlike real Lambda, the function gets no access key, secret or session token. Workaround: don't read credentials in your function; you never need to.

Error #3: import subprocess crashes the function

ModuleNotFoundError: No module named '_signal'

Importing subprocess at module level, or any library that does, crashes the function at cold start. Workaround: keep OS-level modules out of module-level imports.

Error #4: Unknown service inside the function

UnknownServiceError: Unknown service: 'sts'. Valid service names are: sqs, sns, events, eventbridge, dynamodb, logs, cloudwatchlogs, cloudwatch, apigateway, apigatewaymanagementapi, secretsmanager, ss...

boto3 inside the function only covers some services. Oddly, boto3.client("nope") returned a client without raising, so don't trust the absence of an error either.

Workaround: check that every service your function calls is on that list. Call STS from the host instead; that is where my safety guard runs.

Node.js runtime

Error #5: A bundled AWS SDK fails at import

Runtime.ImportModuleError: Error: Cannot find module 'node:zlib'

A bundled SDK needs Node.js core modules the emulator doesn't have. On 1.0.505 it fails on node:process instead. Workaround: leave the SDK out of the bundle, because the runtime provides it: externalModules: ['@aws-sdk/*'] with CDK, or '--external:@aws-sdk/*' with esbuild.

Error #6: The esbuild createRequire banner fails too

Runtime.ImportModuleError: Error: Cannot find module 'node:module'

esbuild's usual banner for CommonJS dependencies imports node:module, which the emulator doesn't have. Workaround: with the SDK left out of the bundle, you don't need the banner.

Finding: The SDK client is a shim too

new DynamoDBClient({}) works with no endpoint and no credentials, but client.config.endpoint is undefined and the client has only a config property. A real v3 client also has middlewareStack. So locally you are not testing the real SDK's middleware, retries or HTTP settings. Anything you configure beyond the defaults may behave differently, or be ignored. I didn't verify which.

Deploying with CDK

Error #7: A route with a path parameter returns 500

500 {"message":"Internal Server Error"}

After a clean deploy, GET /notes and POST /notes worked, but GET /notes/{id} returned 500 for every id. The function was never called. The emulator's log says why:

refusing an invoke: this route's function allows the gateway no invocation for it, so none was made

CDK gives API Gateway permission to call the function on the path /notes/{id}, written literally. The emulator doesn't match that to a real request like /notes/123. I couldn't check how real AWS treats it, so I'm not calling it a bug.

Workaround: give API Gateway a second permission that uses * for the path, and only for local deploys.

  1. In your stack, after you create the function and the HTTP API, add this:
import * as iam from 'aws-cdk-lib/aws-iam';

// Only runs when you deploy with: cdk deploy -c local=true
if (this.node.tryGetContext('local') === 'true') {
  // getNoteFn = the function behind GET /notes/{id}
  // httpApi   = your HttpApi
  getNoteFn.addPermission('LocalEmulatorInvoke', {
    principal: new iam.ServicePrincipal('apigateway.amazonaws.com'),
    sourceArn: `arn:aws:execute-api:${this.region}:${this.account}:${httpApi.apiId}/*/*/notes/*`,
  });
}
  1. Deploy to the emulator with the flag: cdk deploy -c local=true.
  2. Call GET /notes/{id} again. You should get 200 for a note that exists and 404 for one that doesn't.

Without -c local=true, the extra permission isn't added, so your production template doesn't change. If you have other routes with a path parameter, give each of them the same permission.

What the Emulator Can't Tell You

AWS Emulator proves your wiring, not your runtime.

It told me, with real confidence, that API Gateway routes to my function, that my function reads and writes DynamoDB and that my error responses have the right shape. It could not tell me any of these:

  • Whether your IAM is right.
  • Whether your code runs on the real interpreter.
  • Whether your SDK configuration works.
  • Anything involving the network or host files.
  • Warm-start behaviour.

The only proof of those is a real deployment. Use the emulator for the fast inner loop, and keep one deploy to a real AWS account in your pipeline.

Conclusion

AWS Emulator does what it promises. Calls come back in milliseconds, there's no account and no bill, and a fresh start, CDK deploy and test takes a minute or two. For API Gateway, Lambda and DynamoDB, its behaviour was faithful: complete proxy events, the real error shapes, real pagination limits.

But it is a new tool, and it changes every day. The runtimes are stand-ins, the SDK is a shim, and IAM is only partly enforced. So check what your Lambda sees before you build, run your unit tests on the real runtime, guard against touching real AWS, and write down the version you tested on.

The emulator didn't replace AWS for me. It replaced the waiting.

Have you tried it yet? If you hit an error I didn't cover, drop it in the comments and I'll add it here.

References

  1. Test your applications against AWS locally with AWS Emulator, AWS News Blog
  2. What is AWS Emulator?, AWS Emulator User Guide
  3. Getting started with Docker, AWS Emulator User Guide
  4. aws/aws-emulator, GitHub

For more articles, follow my social handles:

來源:DEV Community · dev.to