aws / aws-sam-cli

CLI tool to build, test, debug, and deploy Serverless applications using AWS SAM
https://aws.amazon.com/serverless/sam/
Apache License 2.0
6.51k stars 1.17k forks source link

"sam package" uploads file to s3 even if the Lambda function code hasn't changed #946

Closed rongshengfang closed 4 years ago

rongshengfang commented 5 years ago

Description:

When CodeUri is set to a local directory where the Lambda function code resides, sam package uploads the package to the s3 bucket even if there hasn't been any changes to the local directory. This causes a file to be uploaded to the s3 bucket every time sam package is run, even if there isn't any change to the Lambda function code.

Is there any way for sam to only upload the file when there are changes?

This is how I use the sam package command:

sam build --use-container --template FunctionV1.yaml
sam package --s3-bucket ${my_s3_bucket} --output-template-file FunctionV1-packaged.yaml \
    --region ${AWS_REGION}
sam deploy ...

Please see below for the function definition:

  FunctionV1:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: MyFunctionV1
      Description: MyFunctionV1
      CodeUri: ../src/v1/
      Handler: lambda_function.lambda_handler
      Runtime: python3.7
      Timeout: 120
      MemorySize: 128
      AutoPublishAlias: live
keetonian commented 5 years ago

Transferring to the SAM CLI repo, which handles sam package.

PatButlerTR commented 4 years ago

I have this same problem and I wish there was a native builtin function to calculate the SHA of a file (e.g. Terraform has filesha256()). What I have been doing for my workaround is in my deploy script, after I run my SAM package, but before SAM/cft deploy, I loop through the binaries/code that need to be deployed and I run the following command to get the SHA256:

SHA256=$(openssl dgst -sha256 -binary cmd/$function/release/$function | openssl enc -base64 | tr -d "=+/")

$function is the name of the function in the SAM as well as the name of the binary (GoLang for us, but you could hash any code file). After I get the SHA256 I then insert the "AutoPublishCodeSha256" property in the packaged.yaml with the SHA value using yq. This looks like this:

yq w -i packaged.yaml "Resources.$function.Properties.AutoPublishCodeSha256" "$SHA256"

This will cause SAM to not create a new version if the SHA is the same. It will still upload the code unfortunately and deploy a $LATEST Version, but your alias will still point to the latest "versioned" change (e.g 1,2,3 etc.)

jfuss commented 4 years ago

This should no longer happen with version of SAM CLI after 0.42.0. We now sha the contents of the file: https://github.com/awslabs/aws-sam-cli/pull/1789

Closing