Hello here is my project structure:
-AppName
-Common
-common.js //Global module which i'm using in all functions
-Func1
-index.js
-Func2
-index.js
-template.yaml
And here is template.yaml content:
AWSTemplateFormatVersion: '2010-09-09'
Transform: 'AWS::Serverless-2016-10-31'
Description: An AWS Serverless Specification template describing your function.
Resources:
Func1:
Type: 'AWS::Serverless::Function'
Properties:
Handler: Func1/index.handler
Runtime: nodejs6.10
MemorySize: 512
Timeout: 10
Func2:
Type: 'AWS::Serverless::Function'
Properties:
Handler: Func2/index.handler
Runtime: nodejs6.10
MemorySize: 512
Timeout: 10
When i deploy for example Func2, result package contain all folders inside application, instead only Func2. Is it possible to configure through yaml file, what files will included in result package?
For example if i deploy Func2 i want to see in package next:
-Common
-common.js
-Func2
-index.js
You can use the CodeUri key in SAM and point it to the folder where your code lies for that one function.
So for this function, you'd want to do:
Func2:
Type: 'AWS::Serverless::Function'
Properties:
CodeUri: Func2
Handler: index.handler
Runtime: nodejs6.10
MemorySize: 512
Timeout: 10
Related
myFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: myFunction
Handler: myFunction.lambda_handler
myOtherFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: myOtherFunction
Handler: myOtherFunction.lambda_handler
I want to run a yq command such that for every Type:AWS::Serverless::Function resources, I'd like to grab the value of the Handler and make another attribute under properties called Environment.Variables.HANDLER.
I have following command so far.
yq '(.Resources.[] | select(.Type=="AWS::Serverless::Function") | .Properties.Environment.Variables.HANDLER) += (.Resources.[].Properties.Handler)' test.yaml
Which ends up with
myFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: myFunction
Handler: myFunction.lambda_handler
Environment:
Variables:
HANDLER: myOtherFunction.lambda_handler # This is wrong
myOtherFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: myOtherFunction
Handler: myOtherFunction.lambda_handler
Environment:
Variables:
HANDLER: myOtherFunction.lambda_handler
Where Environment.Variables.HANDLER is replaced with myOtherFunction's Handler for all the functions. How do I respectively grab the value from the particular resource to be replaced?
Use the update operator |= whenever you want to stay in context.
.Resources[]
|= select(.Type=="AWS::Serverless::Function").Properties
|= .Environment.Variables.HANDLER = .Handler
Or use the with function:
with(
.Resources[] | select(.Type=="AWS::Serverless::Function").Properties;
.Environment.Variables.HANDLER = .Handler
)
Both evaluate to:
Resources:
myFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: myFunction
Handler: myFunction.lambda_handler
Environment:
Variables:
HANDLER: myFunction.lambda_handler
myOtherFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: myOtherFunction
Handler: myOtherFunction.lambda_handler
Environment:
Variables:
HANDLER: myOtherFunction.lambda_handler
Note: In your approach, using .Resources.[] a second time started iterating all over again, so all matching items received the last value fetched.
I have am trying to deploy an aws lambda function using the SAM cli. I have some layers defined in the sam template. Testing locally using sam local start-api works quite well. The but deploying using the sam deploy --guided command throws the following error
Error: Failed to create changeset for the stack: sam-app, ex: Waiter ChangeSetCreateComplete failed: Waiter encountered a terminal failure state: For expression "Status" we matched expected path: "FAILED" Status: FAILED. Reason: Template format error: Unresolved resource dependencies [arn:aws:lambda:us-west-1:338231645678:layer:ffmpeg:1] in the Resources block of the template
The SAM template is as follows
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
video-processor-functions
Functions to generate gif and thumbnail from uploaded videos
# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
Function:
Timeout: 3
Tracing: Active
Resources:
VideoProcessorFunctions:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: src/
Handler: app.lambdaHandler
Runtime: nodejs14.x
# timeout in seconds - 2 minutes
Timeout: 120
Layers:
- !Ref VideoProcessorDepLayer
- !Ref arn:aws:lambda:us-west-1:338231645678:layer:ffmpeg:1
Architectures:
- x86_64
Events:
HelloWorld:
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
Properties:
Path: /hello
Method: get
VideoProcessorDepLayer:
Type: AWS::Serverless::LayerVersion
Properties:
LayerName: mh-video-processor-dependencies
Description: Dependencies for sam app [video-processor-functions]
ContentUri: dependencies/
CompatibleRuntimes:
- nodejs14.17
LicenseInfo: 'MIT'
RetentionPolicy: Retain
Outputs:
# ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
# Find out more about other implicit resources you can reference within SAM
# https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
HelloWorldApi:
Description: "API Gateway endpoint URL for Prod stage for Hello World function"
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
VideoProcessorFunctions:
Description: "Generate GIF and Thumnail from Video"
Value: !GetAtt VideoProcessorFunctions.Arn
VideoProcessorFunctionsIamRole:
Description: "Implicit IAM Role created for MH Video Processor function"
Value: !GetAtt VideoProcessorFunctionsRole.Arn
Any ideas what i'm doing wrong?
You are trying to reference a logical id that doesn’t exist.
Just put the layer's ARN of 'ffmpeg':
Layers:
- !Ref VideoProcessorDepLayer
- arn:aws:lambda:us-west-1:338231645678:layer:ffmpeg:1
I'm trying to trigger a Lambda:alias (the alias is key here) on a schedule. The following code errors out with
"SampleLambdaLiveAlias is not valid. Reason: Provided Arn is not in
correct format. (Service: AmazonCloudWatchEvents; Status Code: 400;
Error Code: ValidationException;"
How do I properly target the lambda:alias in CloudFormation? I've tried !Ref, !Sub and just the logical name.
My custom-resource approach to retrieving the latest lambda version appears to be a necessary evil of setting up the "live" alias because AWS maintains old lambda versions, even after you delete the lambda and stack AND a valid version is required for a new alias. If anyone knows a more elegant approach to that problem, please see: how-to-use-sam-deploy-to-get-a-lambda-with-autopublishalias-and-additional-alises
SampleLambdaFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: SampleLambda
AutoPublishAlias: staging
CodeUri: src/
Handler: SampleLambda.handler
MemorySize: 512
Runtime: nodejs12.x
Role: !GetAtt SampleLambdaRole.Arn
SampleLambdaLiveAlias:
Type: AWS::Lambda::Alias
Properties:
FunctionName: !Ref SampleLambdaFunction
FunctionVersion: !GetAtt SampleLambdaGetMaxVersionFunction.version
Name: live
SampleLambdaFunctionScheduledEvent:
Type: AWS::Events::Rule
Properties:
State: ENABLED
ScheduleExpression: rate(1 minute) # same as cron(0/1 * * * ? *)
Description: Run SampleLambdaFunction once every 5 minutes.
Targets:
- Id: EventSampleLambda
Arn: SampleLambdaLiveAlias
Your error is in the last line of the piece of configuration you shared. In order to get the resource ARN you need to use Ref intrinsic function such as, !Ref SampleLambdaLiveAlias:
SampleLambdaFunctionScheduledEvent:
Type: AWS::Events::Rule
Properties:
State: ENABLED
ScheduleExpression: rate(1 minute) # same as cron(0/1 * * * ? *)
Description: Run SampleLambdaFunction once every 5 minutes.
Targets:
- Id: EventSampleLambda
Arn: !Ref SampleLambdaLiveAlias
Be aware that Ref intrinsic function may return different things for different types of resources. For Lambda alias it returns the ARN, just what you need.
You can check the official documentation for more detail.
I am wrapping our AWS SAM deployment in Jenkins as part of our CI/CD pipeline. I only want to add the "live" alias to the lambdas when we are merging for example, yet I want "branch builds" to be without an alias. This allows developers to test the code in AWS without it being "live". Other than sed replacing part of the template.yaml before I run "sam package/deploy" is there some other way to accomplish this?
--UPDATE--
It looks like I can use Parameters to create environments in my lambda, but I don't know how to toggle between them. This would look like:
Parameters:
MyEnv:
Description: Environment of this stack of resources
Type: String
Default: testing
AllowedValues:
- testing
- prod
Then I can reference this w/:
Environment:
Variables:
ENV: !Ref: MyEnv
If someone knows how to toggle this parameter at runtime that solves my problem.
I got this working. My template.yaml:
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
sams-app
Globals:
Function:
Timeout: 3
Parameters:
Stage:
Type: String
Description: Which stage the code is in
Default: test
AllowedValues:
- test
- prod
Resources:
HelloWorldSQSFunction:
Type: AWS::Serverless::Function
Properties:
Role: arn:aws:iam::xxxxxxxxxxxx:role/service_lambda_default1
CodeUri: hello_world/
Handler: app.lambda_handler
Runtime: python3.7
AutoPublishAlias: !Ref Stage
DeploymentPreference:
Type: AllAtOnce
Environment:
Variables:
STAGE: !Ref Stage
Outputs:
HelloWorldSQSFunction:
Description: "Hello World SQS Lambda Function ARN"
Value: !GetAtt HelloWorldSQSFunction.Arn
My lambda code:
import json
import os
def lambda_handler(event, context):
stage = os.environ['STAGE']
print(f"My stage is: {stage}")
return {
"statusCode": 200,
}
And to run it locally (I'm using Cloud9):
DEVELOPER:~/environment/sams-app $ sam local invoke --parameter-overrides Stage=prod
Invoking app.lambda_handler (python3.7)
Fetching lambci/lambda:python3.7 Docker container image......
Mounting /home/ec2-user/environment/sams-app/hello_world as /var/task:ro,delegated inside runtime container
START RequestId: 85da81b1-ef74-1b7d-6ad0-a356f4aa8b76 Version: $LATEST
My stage is: prod
END RequestId: 85da81b1-ef74-1b7d-6ad0-a356f4aa8b76
REPORT RequestId: 85da81b1-ef74-1b7d-6ad0-a356f4aa8b76 Init Duration: 127.56 ms Duration: 3.69 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 22 MB
{"statusCode":200}
One thing to note is that this will cause your "sam validate" to fail. For info on that, see: https://github.com/awslabs/serverless-application-model/issues/778
Special thanks to JLarky for the comment on this thread: aws-sam-local environment variables
I have a SAM template file that is throwing errors while doing sam build: [InvalidResourceException('MyFunction', "Type of property 'Events' is invalid.")]
First off, at the top of my file (at the same level as Globals) I have this event (the idea is to define a CloudWatch schedule that fires every 15 minutes and invokes a lambda):
Events:
Type: Schedule
Properties:
Schedule: rate(15 mins)
name: InvokeEvery15MinutesSchedule
Description: Invoke the target every 15 mins
Enabled: True
And here's what the function looks like:
MyFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: ./path-to-code
Events:
- !Ref InvokeEvery15MinutesSchedule
I was doing this because I saw earlier that the following syntax is valid:
Globals:
Function:
Layers:
- !Ref Layer1
- !Ref Layer1
So, I thought that if I define an event at the top level and reference it inside the lambda, it will work. I want to keep it outside of the Lambda declaration because I want this to apply to several functions.
Can someone help with what I'm doing wrong?
"Events" is a lambda source object that defines the events that trigger this function. The object describing the source of events which trigger the function.
Try this:
MyFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: ./path-to-code
Events:
RateSchedule:
Type: Schedule
Properties:
Schedule: rate(15 mins)
Name: InvokeEvery15MinutesSchedule
Description: Invoke the target every 15 mins
Enabled: True