I have a simple Go AWS lambda function defined using the AWS CDK. I’m developing on an amd64 mac, but deploying an arm64 lambda. CDK commands all work as expected, and the stack correctly builds the arm64 lambda container image and deploys as an arm64 lambda. The function works correctly once deployed.
However, I’m trying to use AWS SAM to locally test the lambda. Since I’m using a container image for the lambda, I first need to build the local test image with sam build
. However, building the image with sam ends up throwing an error related to cross-compilation.
The lambda part of the stack looks like the following:
// Create a new container image
dir, _ := os.Getwd()
ecr_image := awslambda.EcrImageCode_FromAssetImage(jsii.String(filepath.Join(dir, "lambda-image")),
&awslambda.AssetImageCodeProps{
Platform: awsecrassets.Platform_LINUX_ARM64(),
},
)
// Lambda Function
fn := awslambda.NewFunction(stack, jsii.String("appName"),
&awslambda.FunctionProps{
Code: ecr_image,
Runtime: awslambda.Runtime_FROM_IMAGE(),
Handler: awslambda.Handler_FROM_IMAGE(),
FunctionName: jsii.String("appName"),
Timeout: awscdk.Duration_Seconds(jsii.Number(15)),
Environment: &lambda_env,
Architecture: awslambda.Architecture_ARM_64(),
}
)
The Dockerfile looks like this:
FROM --platform=$BUILDPLATFORM golang:1.22.4-alpine3.20 AS builder
WORKDIR /
# Disable cgo to create a static binary.
ENV CGO_ENABLED="0"
# Compile for arm64 Linux
ARG TARGETOS
ARG TARGETARCH
ENV GOOS=$TARGETOS
ENV GOARCH=$TARGETARCH
... building image here ...
# Copy artifacts to a clean image
FROM scratch
WORKDIR /
EXPOSE 5000
COPY --from=builder /app /
CMD ["/app"]
Following the AWS docs, I first try to run the command below to build the local container image to use for testing:
sam build --use-container -t ./cdk.out/AppNameStack.template.json
But the build fails with the error
Error: failed to parse platform : "" is an invalid component of "": platform specifier component must match "^[A-Za-z0-9_-]+$": invalid argument
This is obviously related to the build not correctly receiving the platform argument and interpolating the variables in the Dockerfile. However, if I change the Dockerfile to use static platforms (i.e. --platform=linux/amd64
for the build image and --platform=linux/arm64
for the final image), I then get the following error
Error: failed to get destination image "sha256:def...": image with reference sha256:def... was found but does not match the specified platform: wanted linux/arm64, actual: linux/amd64
Any ideas what’s going on here? It’s strange that it all works fine with CDK, but not with SAM.
mkmiller6 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.