We are deploying a lambda using CloudFormation SAM templates.
We would like to package the lambda into an S3 bucket, then deploy the AWS::Serverless::Function in multiple regions.
However, lambda code must reside in the same region as where it's being deployed.
AWS have documented how to work around this problem, essentially by creating another lambda CopyZips
to copy the zip file to each region where you want it deployed, and a new s3 bucket LambdaZipsBucket
in each region to put it in. Then your lambda function looks like this:
MyFunction:
DependsOn: CopyZips
Type: AWS::Lambda::Function
Properties:
Code:
S3Bucket: !Ref 'LambdaZipsBucket'
S3Key: !Sub '${QSS3KeyPrefix}functions/packages/MyFunction/lambda.zip'
The problem is, that relies on knowing the exact path to the zip file. In our case we are using SAM template substitution, so we never specify the S3 bucket or S3 key - instead our Function looks like this:
MyFunction:
Type: 'AWS::Serverless::Function'
Properties:
CodeUri: ./MyCompany.Service.Broker.Public
The S3 bucket is not referenced at all in the CloudFormation template. And the lambda, which you can see by browsing the bucket, has a name like :
ApiFunction-CodeUri-2342873t823t482346-97346583746583745.zip
This is because there are lots of similar zips, created at build time. The Serverless template model will decode this, and if we look in the CloudFormation console, in the template tab, and select "view processed template", we can see the S3Bucket and S3Key fields populated correctly.
The build is done in Azure devops, using the AmazonWebServices.aws-vsts-tools.LambdaNETCoreDeploy.LambdaNETCoreDeploy@1
task, where we specify the bucket name and region, but again, not the name of the zip file.
Given that I have no access in the template to the exact path to the lambda zip file, how am I supposed to automate the copy of the zip file to a local bucket?
UPDATE:
I tried adding the following line in Properties, just before CodeUri:
Code:
S3Bucket: !Ref 'LambdaZipsBucket'
However, I got the following error on deployment:
Resource with id [ApiFunction] is invalid. property Code not defined for resource of type AWS::Serverless::Function
You can try using policy with AWS::Serverless::Function and give relevant permissions. Which look allowed in format.