Skip to content

feat(package): Add sam package support for MicrovmImage - #9399

Merged
licjun merged 11 commits into
aws:developfrom
licjun:feat-microvm-image-package
Nov 10, 2026
Merged

licjun merged 11 commits into
aws:developfrom
licjun:feat-microvm-image-package

Conversation

@licjun

@licjun licjun commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Which issue(s) does this change fix?

Part of #9283. #9357 added sam build support; this PR adds sam package support for local MicrovmImage code, which sam deploy uses too.

Why is this change necessary?

A MicrovmImage is deployed as a zip of its source directory (Dockerfile plus application code), which the MicroVM service builds remotely. Until now sam package failed for a MicrovmImage with local code (a placeholder added in #9357), so users had to zip and upload the source themselves.

How does it address the issue?

The placeholder exporters in samcli/lib/package/packageable_resources.py are replaced with exporters that upload the code:

  • AWS::Serverless::MicrovmImage (CodeUri): a ResourceZip with FORCE_ZIP. A local directory is zipped and uploaded, and CodeUri is set to the S3 URI. This matches AWS::Serverless::Function.
  • AWS::Lambda::MicrovmImage (CodeArtifact): CloudFormation requires CodeArtifact: {Uri: s3://...}. A local path is accepted as {Uri: ./src} or as a plain string, the form CDK templates and built templates use, and is written back as {Uri: <S3 URI>}. get_property_value reads the S3 URI from either form, for sam delete.
  • For both types, a local .zip file is uploaded as is. Intrinsics are left unchanged, and an S3 URI is not uploaded again. A missing code path is not packaged (PACKAGE_NULL_PROPERTY = False), so the template directory is never uploaded in its place.
  • Fn::ForEach templates (--language-extensions): the packaging map is derived from RESOURCES_WITH_LOCAL_PATHS, which already lists both types. Before expansion, a local AWS::Lambda::MicrovmImage CodeArtifact given as a plain string is wrapped as {Uri: ...}, so a dynamic ./${N} is packaged like {Uri: ./${N}} and ends as {Uri: !FindInMap [...]}.

A CodeUri or CodeArtifact that points at a single file other than a .zip, such as the Dockerfile, fails with a message that suggests the directory that contains it, as sam build does. Otherwise the package step does not validate the contents of the source, the same as for functions.

The PR also improves a sam build error: when a MicrovmImage CodeUri is a file, a .zip now gets its own message (point at the source directory to build locally; sam package uploads the .zip as is), and any other file, such as a Dockerfile, gets a message that suggests the directory that contains it.

What side effects does this change have?

  • sam package and sam deploy now upload local MicrovmImage code instead of failing.
  • For AWS::Lambda::MicrovmImage, a CodeArtifact given as a plain string, local path or S3 URI, is written as {Uri: ...} in the packaged template, the object form CloudFormation requires. An S3 URI is not uploaded again. This matches the Lambda function and layer exporters, which write an S3 string Code or Content as {S3Bucket, S3Key}.

Testing

  • Unit tests in test_artifact_exporter.py cover a local directory, both CodeArtifact forms, a local .zip, S3 URIs, intrinsics, a missing value, a missing directory, get_property_value, and a full template export.
  • Integration tests: the zip package tests now also run an AWS::Serverless::MicrovmImage and an AWS::Lambda::MicrovmImage template, in every test that runs the function templates.
  • sam build followed by sam package on the built template, with the S3 upload stubbed, for both resource types and for the Fn::ForEach fixture.
  • End to end in a real account (us-east-1, base image al2023-1 version 2): sam build, then sam deploy --resolve-s3 --capabilities CAPABILITY_IAM on an AWS::Serverless::MicrovmImage with a local CodeUri and no BuildRoleArn. The stack was created, the uploaded zip contained the Dockerfile and app code at its root, the transformed AWS::Lambda::MicrovmImage had CodeArtifact: {Uri: <that S3 URI>}, and the MicroVM service built the image (state: CREATED, active version 1.0). sam delete then removed the stack, the image, and the uploaded zip.

Mandatory Checklist

PRs will only be reviewed after checklist is complete

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

sam package now zips a MicrovmImage source directory, uploads it to S3
and points the template at the S3 URI. The MicroVM service builds the
image from that zip. This replaces the exporters that failed for local
code.

- AWS::Serverless::MicrovmImage: CodeUri is set to the S3 URI.
- AWS::Lambda::MicrovmImage: CodeArtifact is written as {Uri: <S3 URI>},
  which CloudFormation requires. A local path is accepted as {Uri: ...}
  or as a plain string, the form CDK and sam build use.

S3 URIs and intrinsics are left unchanged. A missing code path is not
packaged, so the template directory is never uploaded instead.
A MicrovmImage CodeUri that is a file gave one message that always
mentioned .zip files, even for a file such as a Dockerfile. For a .zip,
explain that sam build needs the source directory and that sam package
uploads the .zip as is. For any other file, suggest the directory that
contains it.
@github-actions github-actions Bot added area/build sam build command pr/internal labels Nov 3, 2026
@aws-sam-tooling-bot

aws-sam-tooling-bot Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

🧪 Hands-on test: No problems observed in 9 scenarios

Commit 54a204a · build LambdaToolingHandsOn-Docker:20a6993f-edf3-403c-88f6-d2683f076131. The plan's scenarios ran on an isolated build host; a problem is reported only if it reproduced at least twice. Passing scenarios show only that these checks behaved as expected, not that the change is correct.

Scenarios

Scenario Planned check Result Runner's note
S1 Main path for AWS::Serverless::MicrovmImage: a local CodeUri directory (relative to the template dir, including a path … ✅ pass Head: sam package exit 0 with two FAKE_S3_UPLOAD lines. HelloImage CodeUri s3://fake-bucket/82186afe507d937ebd42ea47e3032aa1 and SpacedImage (CodeUri 'my app ü') s3://fake-bucket/cf2f997d2f58a318c2d6…
S2 AWS::Lambda::MicrovmImage CodeArtifact forms: {Uri: dir} and plain-string dir are uploaded and written as {Uri: S3 URI}… ✅ pass Head: exit 0. UriForm and StringForm both get CodeArtifact {"Uri": "s3://fake-bucket/82186afe..."} (same md5), and the zip lists ['Dockerfile', 'app.py']. S3String is wrapped as {"Uri": "s3://existin…
S3 A local .zip is uploaded byte-for-byte as is (not zipped again) for CodeUri, CodeArtifact {Uri: x.zip} and plain-string… ✅ pass The plan's template has no Name property, so the SAM translator rejects it on both head and base ('Missing required property Name'; log 07, and log 08 for base). I added Name and reran. Head: exit 0.…
S4 Error and missing-value paths the PR adds: a non-zip single file (the Dockerfile, a corrupt .zip) fails and suggests it… ✅ pass Head (Name added): cases a and b exit 1 with "'.../s4/app/Dockerfile' is a file. A MicrovmImage source must be a directory containing a Dockerfile, or a .zip of one, for example '.../s4/app'". Case d…
S5 Fn::ForEach with --language-extensions: a plain-string CodeArtifact './${N}' and the {Uri: './${M}'} form are packaged … ✅ pass Head (Name added) with --language-extensions: exit 0. ${N}CfnImage CodeArtifact = {"Uri": {"Fn::FindInMap": ["SAMUriImages", {"Ref": "N"}, "Uri"]}}, ${N}SamImage CodeUri = Fn::FindInMap [SAMCodeUriIm…
S6 The new warning when the MicrovmImage source directory (here the project root, CodeUri '.') contains .aws-sam and .git,… ✅ pass Head (Name added): exit 0. Two warnings are logged, one for RootImage naming CodeUri and one for CfnRootImage naming CodeArtifact.Uri: "directory '.../s6' contains .aws-sam and .git, and the whole di…
S7 Main user flow from the PR description: sam build (Docker), then sam package of .aws-sam/build/template.yaml, for AWS::… ✅ pass The dev install (SAM_CLI_DEV=1) provides 'samdev', not 'sam', so the first attempt (log 18) failed with 'sam: command not found'. The rerun used samdev. Head: sam build exit 0 with 'Build Succeeded' …
S8 Changed sam build errors: a valid .zip CodeUri gets the new '.zip file' message, and a Dockerfile CodeUri gets a messag… ✅ pass Head (Name added, samdev): both builds exit 1 before any Docker build. ZipImage prints "CodeUri '.../s8/app.zip' for MicrovmImage 'ZipImage' is a .zip file. sam build builds MicrovmImages from a sour…
S9 The PR's unit tests and the surrounding package and build suites pass, so existing function and layer packaging still w… ✅ pass Head: tests/unit/lib/package plus tests/unit/commands/package: 526 passed, 22 subtests passed. tests/unit/lib/build_module/test_app_builder.py: 173 passed. The named PR tests (TestMicrovmImageResourc…
Runner's notes in full
  • S1: Head: sam package exit 0 with two FAKE_S3_UPLOAD lines. HelloImage CodeUri s3://fake-bucket/82186afe507d937ebd42ea47e3032aa1 and SpacedImage (CodeUri 'my app ü') s3://fake-bucket/cf2f997d2f58a318c2d64f87721fef62. Both zips list ['Dockerfile', 'app.py'] at the root. Base: exit 1 with 'sam package does not support local code for AWS::Serverless::MicrovmImage yet'. A JSONDecodeError traceback about ~/.aws-sam/metadata.json in the head log came from running head and base at the same time; it did not affect the result.
  • S2: Head: exit 0. UriForm and StringForm both get CodeArtifact {"Uri": "s3://fake-bucket/82186afe..."} (same md5), and the zip lists ['Dockerfile', 'app.py']. S3String is wrapped as {"Uri": "s3://existing-bucket/src.zip"}. S3Uri and RefUri ({Ref: SrcUri}) are unchanged. The store holds 1 file. Base: exit 1 with the 'does not support local code ... set CodeArtifact to its S3 URI' message.
  • S3: The plan's template has no Name property, so the SAM translator rejects it on both head and base ('Missing required property Name'; log 07, and log 08 for base). I added Name and reran. Head: exit 0. SamZip CodeUri, CfnZip and CfnZipString CodeArtifact {Uri} all point to s3://fake-bucket/8400a545663bf511d1306d63d50d0941. The store holds 1 object and cmp prints SAME_BYTES against app.zip, so the zip is not wrapped again. Base: exit 1 with the placeholder error.
  • S4: Head (Name added): cases a and b exit 1 with "'.../s4/app/Dockerfile' is a file. A MicrovmImage source must be a directory containing a Dockerfile, or a .zip of one, for example '.../s4/app'". Case d (corrupt broken.zip) exits 1 with the same message, suggesting '.../s4'. Cases c and e exit 1 with 'refers to a file or folder that does not exist .../missing' (property CodeArtifact.Uri for c, CodeUri for e). Combined case f fails in the SAM translator ('Missing required property CodeUri' for SamNoCode) on head and base, so the SAM exporter never sees a missing CodeUri. A CFN-only split (log 12) exits 0 and leaves CfnNoCode without CodeArtifact. uploads=0 in every case. Base: a-e all fail with the placeholder message.
  • S5: Head (Name added) with --language-extensions: exit 0. ${N}CfnImage CodeArtifact = {"Uri": {"Fn::FindInMap": ["SAMUriImages", {"Ref": "N"}, "Uri"]}}, ${N}SamImage CodeUri = Fn::FindInMap [SAMCodeUriImages, Ref N, CodeUri], and ${M}UriImage CodeArtifact = {"Uri": {"Fn::FindInMap": ["SAMUriUriImages", {"Ref": "M"}, "Uri"]}}. No ForEach body keeps a local path. All Mappings values are s3://fake-bucket URIs. Alpha (75debd41...) and Beta (d74e5233...) differ, and every zip lists ['Dockerfile', 'app.py']. StaticImage CodeArtifact = {"Uri": s3://fake-bucket/75debd41...}, the Alpha md5. Base: exit 1 with the placeholder error on StaticImage.
  • S6: Head (Name added): exit 0. Two warnings are logged, one for RootImage naming CodeUri and one for CfnRootImage naming CodeArtifact.Uri: "directory '.../s6' contains .aws-sam and .git, and the whole directory is uploaded...". Both resources point at s3://fake-bucket/8c1a4152a8a514c9011c88b8c1187036. The zip contains .aws-sam/build/marker, .git/HEAD, Dockerfile, app.py and template.yaml, so .git and .aws-sam are included, as the warning says. Base: exit 1 with the placeholder error.
  • S7: The dev install (SAM_CLI_DEV=1) provides 'samdev', not 'sam', so the first attempt (log 18) failed with 'sam: command not found'. The rerun used samdev. Head: sam build exit 0 with 'Build Succeeded' and the expected arm64-on-x86 warning. The built template has CodeUri ../../app, CodeArtifact Uri ../../app and CodeArtifact ../../app. sam package exit 0. HelloImage CodeUri and the CfnImage and CdkStyleImage CodeArtifact {Uri} all point to s3://fake-bucket/82186afe..., and the zip lists ['Dockerfile', 'app.py'] (source dir, not .aws-sam/build). Base: build succeeds, package exits 1 with the placeholder error.
  • S8: Head (Name added, samdev): both builds exit 1 before any Docker build. ZipImage prints "CodeUri '.../s8/app.zip' for MicrovmImage 'ZipImage' is a .zip file. sam build builds MicrovmImages from a source directory containing a Dockerfile; point CodeUri at that directory to build locally. sam package uploads a .zip as is." FileImage prints "CodeUri '.../s8/app/Dockerfile' ... is a file. CodeUri must be a directory containing a Dockerfile, for example '.../s8/app'." Base prints the old "... is a file. CodeUri must be a directory containing a Dockerfile; sam build cannot build a MicrovmImage from a .zip file." for both.
  • S9: Head: tests/unit/lib/package plus tests/unit/commands/package: 526 passed, 22 subtests passed. tests/unit/lib/build_module/test_app_builder.py: 173 passed. The named PR tests (TestMicrovmImageResource, TestNestedStackMicrovmCodeArtifactString, TestWrapMicrovmImageCodeArtifactStrings, test_export_wraps_string_microvm_code_artifact_in_foreach, test_build_microvm_image_raises_when_code_uri_is_a_file) all pass: 15 passed.

🤖 Automated hands-on test — not a review approval · model claude-opus-5.5 · Kiro kiro-cli 2.33.1 · build LambdaToolingHandsOn-Docker:20a6993f-edf3-403c-88f6-d2683f076131 · commit 54a204a

History (7)
Commit Result When (UTC) Build
54a204a No problems observed 2026-11-10 00:17 LambdaToolingHandsOn-Docker:20a6993f-edf3-403c-88f6-d2683f076131
6d00e9a Timed out / incomplete 2026-11-07 00:19 LambdaToolingHandsOn-Docker:a5b88684-a6ab-4e26-bbb9-82ab1b5852cc
2bf3e89 No problems observed 2026-11-05 19:17 LambdaToolingHandsOn-NoDocker:ed14a6c1-07c6-448e-ae1a-94e6c9ad523e
dce15e4 No problems observed 2026-11-05 19:04 LambdaToolingHandsOn-Docker:dedd8c4a-7398-4ffb-b287-980afd54053c
5e72d0c No problems observed 2026-11-04 00:33 LambdaToolingHandsOn-Docker:510c9889-1c99-464b-a94f-83895502e134
1d56090 No problems observed 2026-11-04 00:01 LambdaToolingHandsOn-NoDocker:bc4fa66a-4af4-4a42-82a6-f96119885cd5
2798834 Problems reproduced: sam package --language-extensions crashes with TypeError for AWS::Lambda::Micro…; sam package accepts a MicrovmImage CodeUri pointing at a single file (Dockerfil… 2026-11-03 23:40 LambdaToolingHandsOn-Docker:3262159f-1e6b-488b-9e60-e78b2f5c07ac

@aws-sam-tooling-bot aws-sam-tooling-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧪 Hands-on test reproduced 2 new problems on commit 2798834. Commands and evidence are in the hands-on comment.

  1. [BUG] sam package --language-extensions crashes with TypeError for AWS::Lambda::MicrovmImage in Fn::ForEach using plain-string CodeArtifact: ./${N} · medium · samcli/lib/package/language_extensions_packaging.py:342
  2. [UX] sam package accepts a MicrovmImage CodeUri pointing at a single file (Dockerfile) and silently uploads a zip with only that file · low · samcli/lib/package/packageable_resources.py:774

🤖 Automated hands-on test — not a review approval


temp_dir = None
if is_local_file(local_path) and not is_zip_file(local_path):
temp_dir = copy_to_temp_dir(local_path)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧪 Hands-on: [UX] sam package accepts a MicrovmImage CodeUri pointing at a single file (Dockerfile) and silently uploads a zip with only that file (reproduced 2 times in S3). Commands and evidence: hands-on comment.

Add an AWS::Serverless::MicrovmImage and an AWS::Lambda::MicrovmImage
template and run them in every zip package test that runs the
function templates.
With --language-extensions, an AWS::Lambda::MicrovmImage in Fn::ForEach
with a plain-string CodeArtifact such as ./${N} crashed with a
TypeError. The exporter writes CodeArtifact back as {Uri: <S3 URI>}, and
copying CodeArtifact.Uri into a body that still held a string failed. A
dynamic string would also have become an Fn::FindInMap string, while
CloudFormation requires the object form.

Before expansion, wrap a local string CodeArtifact as {Uri: <string>},
so it is packaged like the {Uri: ./${N}} form. S3 URIs and intrinsics
are left unchanged.
A MicrovmImage CodeUri or CodeArtifact that pointed at a single file,
such as the Dockerfile, was zipped on its own and uploaded, so files the
Dockerfile copies were left out and the remote build failed. Fail
instead, and suggest the directory that contains the file, as sam build
does. A .zip is still uploaded as is.
@licjun
licjun marked this pull request as ready for review November 4, 2026 00:39
@licjun
licjun requested a review from a team as a code owner November 4, 2026 00:39
@licjun
licjun requested a review from bnusunny November 4, 2026 00:39
@licjun

licjun commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor Author

Both problems are fixed:

  1. sam package --language-extensions crash for a plain-string CodeArtifact: ./${N} in Fn::ForEach: fixed in 84f3254. The exporter writes CodeArtifact back as {Uri: <S3 URI>}, and copying CodeArtifact.Uri into a Fn::ForEach body that still held a string failed. Before expansion, a local string CodeArtifact is now wrapped as {Uri: ...}, so it is packaged like the {Uri: ./${N}} form and ends as {Uri: !FindInMap [...]}, the object form CloudFormation requires. S3 URIs and intrinsics are left unchanged.
  2. A CodeUri pointing at a single file (Dockerfile) uploaded a zip with only that file: fixed in 5e72d0c. For both MicrovmImage types, a single file that is not a .zip now fails before any upload, with a message that suggests the directory that contains it, as sam build does. A .zip is still uploaded as is.

@bnusunny bnusunny left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good overall. One test gap to fix before merge, plus three small nits. I also ran sam package --language-extensions end to end, and CloudFormation created MicroVM images from the packaged template.

End-to-end test (5e72d0c, us-east-1)

I used one template with two Fn::ForEach loops over [Alpha, Beta]:

  • AWS::Lambda::MicrovmImage with CodeArtifact: ./${Name} as a plain string. This is the form that crashed before 84f3254.
  • AWS::Serverless::MicrovmImage with CodeUri: ./${Name}.

sam package uploaded one zip per source directory. It kept the Fn::ForEach blocks and wrote CodeArtifact: {Uri: !FindInMap [...]} and CodeUri: !FindInMap [...], with the per-name S3 URIs in Mappings. I deployed the packaged template with aws cloudformation deploy, so SAM did not package it again. All four images reached CREATE_COMPLETE, and the MicroVM service built each one from its zip.

The packaging itself had no problems. Two notes for anyone repeating the test:

  • AWS::Lambda::MicrovmImage fails CloudFormation early validation unless BuildRoleArn, Hooks, CpuConfigurations, Logging, Resources, EnvironmentVariables, EgressNetworkConnectors, AdditionalOsCapabilities and Description are all set. The SAM transform fills these in, so tests/integration/testdata/package/aws-lambda-microvmimage.yaml packages but would not deploy as written.
  • The image must start a long-running server. With the microvm-image-foreach build fixtures, which have no CMD, the Docker build succeeds but the image never stabilizes.

Findings

  1. Test gap (please fix). The two calls to wrap_microvm_image_code_artifact_strings have no tests (package_context.py:264, artifact_exporter.py:318). If you delete either call, every package unit test still passes. Deleting the top-level one brings back the TypeError from the hands-on report. The new tests call the helper directly, and no integ fixture uses Fn::ForEach. A PackageContext-level test with a plain-string ./${N} in Fn::ForEach, plus a nested-stack version, would cover both calls.
  2. Nit. FORCE_ZIP = True on both MicroVM exporters never takes effect. _check_microvm_image_source rejects single non-zip files first, and LambdaMicrovmImageResource.export never reads the flag. It suggests that a single file gets zipped, which can't happen. Drop it or add a comment.
  3. Low. A plain-string S3 CodeArtifact: s3://... is left as a string, but CloudFormation requires {Uri: ...}. Local strings are already rewritten into that form, so S3 strings could be too. This isn't a regression.
  4. Nit. sam build decides whether a file is a .zip from its extension (app_builder.py:1219). sam package checks whether the file really is a zip. So a corrupt x.zip gets "sam package uploads a .zip as is" from build, and then package rejects it as a file.

Checks: CI is green. 695 unit tests pass in the package and build suites. I broke 11 of the new branches one at a time to see whether a test fails. 9 were caught; the two that weren't are the calls in finding 1.

bnusunny

This comment was marked as duplicate.

Neither call to wrap_microvm_image_code_artifact_strings had a test, so
removing one still passed. Package a plain-string CodeArtifact in
Fn::ForEach through PackageContext and through a nested stack, and check
that each ends as {Uri: Fn::FindInMap}.
A single non-zip file is rejected before export, and the Lambda exporter
never read the flag, so FORCE_ZIP had no effect and suggested that a
single file is zipped.
sam build chose its .zip message from the file extension, while sam
package checks the content. A corrupt x.zip was told that sam package
uploads it as is, and then package rejected it as a file. Check the
content in build too.
CloudFormation requires AWS::Lambda::MicrovmImage CodeArtifact as an
object, but an S3 URI given as a plain string was left as a string, so
the packaged template could not deploy. Local strings were already
rewritten. Write S3 strings as {Uri: <S3 URI>} too, without uploading,
as the Lambda function and layer exporters write an S3 string Code or
Content as {S3Bucket, S3Key}. This also applies inside Fn::ForEach.
@licjun

licjun commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

@bnusunny Thanks for the review and the end-to-end run. All four findings are addressed:

  1. Test gap: 7b00d8e adds a PackageContext test and a nested-stack test, each packaging a plain-string CodeArtifact: ./${N} in Fn::ForEach and checking for {Uri: Fn::FindInMap}. Removing either wrap_microvm_image_code_artifact_strings call now fails its test, and only that one.
  2. Unused FORCE_ZIP: removed from both MicrovmImage exporters in 7b5feca. Directories are still zipped, a .zip is uploaded as is, and a single other file is rejected.
  3. S3 string CodeArtifact: 2bf3e89 writes it as {Uri: s3://...} without uploading, like the Lambda function and layer exporters, which write an S3 string Code or Content as {S3Bucket, S3Key}. This also applies inside Fn::ForEach, including s3://bucket/${N}.zip.
  4. .zip detection: dce15e4 makes sam build check the file content, as sam package does, so a corrupt x.zip gets the "is a file" message from both. The build-all skip (is_microvm_image_buildable) still goes by the extension, like the layer check.

On your deploy notes: aws-lambda-microvmimage.yaml is only used by the package integ tests, so I left it as is.

@licjun
licjun requested a review from bnusunny November 5, 2026 21:51

@bnusunny bnusunny left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, the four new commits cover findings 1-3. Finding 4 is only fixed on a path the CLI never reaches.

What's fixed (2bf3e89)

  • Test gap: deleting either wrap_microvm_image_code_artifact_strings call now fails exactly one named test (the new PackageContext test and the new nested-stack test).
  • FORCE_ZIP is gone.
  • An S3 string CodeArtifact is now written as {Uri: ...}, at the top level and inside Fn::ForEach. I ran sam package --language-extensions on CodeArtifact: s3://bucket/${N}.zip in a Fn::ForEach. The previous head wrote a bare CodeArtifact: !FindInMap [...], which CloudFormation rejects. This head writes {Uri: !FindInMap [...]}.

Still open: finding 4
sam build never reaches the new zipfile.is_zipfile check for a .zip path. BuildContext.is_microvm_image_buildable skips any CodeUri ending in .zip first, by extension (build_context.py:1697, from #9357). With a corrupt broken.zip, sam build still prints "Skipping MicrovmImage ...: CodeUri points to a .zip file", and sam package then rejects it as a file. The new ./broken.zip subtest mocks is_zipfile and calls _build_microvm_image directly, so it covers a path the CLI never takes, and its comment ("a corrupt .zip is reported as a file") doesn't match what users see.

Two ways to fix it: use zipfile.is_zipfile in is_microvm_image_buildable as well, or revert dce15e4 and leave this rare edge case alone. Either is fine with me; the first keeps build and package consistent.

Checks: CI is green. 894 unit tests pass across the package and build suites. I broke each new branch one at a time, and each break fails a named test.

The zip content check in _build_microvm_image is reached for a .zip only
when the image is the build target, since building all resources skips
a CodeUri ending in .zip first. Say so in the code and test comments.
@licjun

licjun commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

@bnusunny Thanks for checking. The new check is reached when the image is the build target: with CodeUri: ./broken.zip (a text file), on this head:

$ sam build Img
Error: CodeUri '.../broken.zip' for MicrovmImage 'Img' is a file. CodeUri must be a directory containing a Dockerfile, for example '...'.

Before dce15e4, the same command said it "is a .zip file" that "sam package uploads as is", and sam package then rejected it. A targeted build does not filter .zip, the same as for functions and layers, so it reaches _build_microvm_image.

You're right that building all resources still skips it by extension:

$ sam build
Skipping MicrovmImage Img: CodeUri points to a .zip file, not a buildable source directory.
Build Succeeded

I'd keep that as is. It matches is_layer_buildable, the build does not use the file, and sam package checks the content and rejects a corrupt one before anything is uploaded. I updated the code and test comments in 6d00e9a to say the check is reached only for a targeted build.

bnusunny
bnusunny previously approved these changes Nov 9, 2026

@bnusunny bnusunny left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right, a targeted sam build <image> reaches the new check. I'd only tried building all resources. Keeping the full-build skip to match layers makes sense. LGTM.

code_uri = resource_dict.get(self.PROPERTY_NAME)
if isinstance(code_uri, str) and code_uri and not is_s3_protocol_url(code_uri):
_check_microvm_image_source(resource_id, self.PROPERTY_NAME, code_uri, parent_dir)
super().export(resource_id, resource_dict, parent_dir)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not blocking, just curious. this zips everything under CodeUri as is, so with the Dockerfile at the project root (CodeUri: .) we'd also upload .aws-sam/, .git/, etc. And since the built template points back at the source dir, running sam build first doesn't change that. Does the MicroVM service respect .dockerignore on its end? If not might be worth skipping .aws-sam at least, maybe as a follow-up.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for catching this. You're right: the whole CodeUri directory is zipped as is, so with CodeUri: . the upload includes .aws-sam/, .git/ and anything else in the project root, and sam build doesn't change that because the built template points back at the source directory. I haven't confirmed whether the MicroVM service applies .dockerignore, but even if it does, that only affects the image, not what is uploaded to S3.

I went with two things instead of excluding files in SAM CLI:

  1. Warn. 54a204a warns when the source directory contains .aws-sam or .git:
    MicrovmImage 'MyImage': CodeUri directory '/path/to/my-app' contains .aws-sam and .git, and the whole directory is uploaded. Put the Dockerfile and application code in a subdirectory and point CodeUri at it, or point CodeUri at a prepared .zip.
    
  2. Document it. I'll add a note to the public AWS::Serverless::MicrovmImage docs that the directory is uploaded as is, and recommend keeping the Dockerfile and application code in their own subdirectory (CodeUri: ./app) or pointing CodeUri at a prepared .zip.

The reason for not excluding is that there are too many corner cases for an exclusion list to cover. Skipping .aws-sam still uploads .git, .env, node_modules and so on, and it misses --build-dir or --cache-dir locations under CodeUri. Honoring .dockerignore would cover more, but it needs its own design (for example, the Dockerfile must always be kept), and it would make MicrovmImage packaging differ from functions, where SAM CLI doesn't filter CodeUri either. The subdirectory layout avoids the problem completely, so the warning points users there.

ckawl
ckawl previously approved these changes Nov 9, 2026
sam package zips a MicrovmImage source directory as is. When CodeUri is
the project root, which the built template still points at after sam
build, .aws-sam and .git are uploaded with the source. Warn about them,
and suggest putting the Dockerfile and application code in a
subdirectory or using a prepared .zip.
@licjun
licjun dismissed stale reviews from ckawl and bnusunny via 54a204a November 10, 2026 00:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/build sam build command pr/internal

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants