======================================== Examples for serverless.xml ======================================== Contents: ========== * Reference Template * Query string body mapping template * Best Cors Reference Reference Template ====================== : # # # # # Serverless.yml Reference # Here is a list of all available properties in serverless.yml when the provider is set to aws. # serverless.yml service: name: myService awsKmsKeyArn: arn:aws:kms:us-east-1:XXXXXX:key/some-hash # Optional KMS key arn which will be used for encryption for all functions frameworkVersion: ">=1.0.0 <2.0.0" provider: name: aws runtime: nodejs8.10 stage: ${opt:stage, 'dev'} # Set the default stage used. Default is dev region: ${opt:region, 'us-east-1'} # Overwrite the default region used. Default is us-east-1 stackName: custom-stack-name # Use a custom name for the CloudFormation stack apiName: custom-api-name # Use a custom name for the API Gateway API websocketsApiName: custom-websockets-api-name # Use a custom name for the websockets API websocketsApiRouteSelectionExpression: $request.body.route # custom route selection expression profile: production # The default profile to use with this service memorySize: 512 # Overwrite the default memory size. Default is 1024 timeout: 10 # The default is 6 seconds. Note: API Gateway current maximum is 30 seconds logRetentionInDays: 14 # Set the default RetentionInDays for a CloudWatch LogGroup deploymentBucket: name: com.serverless.${self:provider.region}.deploys # Deployment bucket name. Default is generated by the framework serverSideEncryption: AES256 # when using server-side encryption tags: # Tags that will be added to each of the deployment resources key1: value1 key2: value2 deploymentPrefix: serverless # The S3 prefix under which deployed artifacts should be stored. Default is serverless role: arn:aws:iam::XXXXXX:role/role # Overwrite the default IAM role which is used for all functions cfnRole: arn:aws:iam::XXXXXX:role/role # ARN of an IAM role for CloudFormation service. If specified, CloudFormation uses the role's credentials versionFunctions: false # Optional function versioning environment: # Service wide environment variables serviceEnvVar: 123456789 endpointType: regional # Optional endpoint configuration for API Gateway REST API. Default is Edge. apiKeys: # List of API keys to be used by your service API Gateway REST API - myFirstKey - ${opt:stage}-myFirstKey - ${env:MY_API_KEY} # you can hide it in a serverless variable apiGateway: # Optional API Gateway global config restApiId: xxxxxxxxxx # REST API resource ID. Default is generated by the framework restApiRootResourceId: xxxxxxxxxx # Root resource ID, represent as / path restApiResources: # List of existing resources that were created in the REST API. This is required or the stack will be conflicted '/users': xxxxxxxxxx '/users/create': xxxxxxxxxx apiKeySourceType: HEADER # Source of API key for usage plan. HEADER or AUTHORIZER. minimumCompressionSize: 1024 # Compress response when larger than specified size in bytes (must be between 0 and 10485760) description: Some Description # optional description for the API Gateway stage deployment usagePlan: # Optional usage plan configuration quota: limit: 5000 offset: 2 period: MONTH throttle: burstLimit: 200 rateLimit: 100 stackTags: # Optional CF stack tags key: value iamManagedPolicies: # Optional IAM Managed Policies, which allows to include the policies into IAM Role - arn:aws:iam:*****:policy/some-managed-policy iamRoleStatements: # IAM role statements so that services can be accessed in the AWS account - Effect: 'Allow' Action: - 's3:ListBucket' Resource: Fn::Join: - '' - - 'arn:aws:s3:::' - Ref: ServerlessDeploymentBucket stackPolicy: # Optional CF stack policy. The example below allows updates to all resources except deleting/replacing EC2 instances (use with caution!) - Effect: Allow Principal: "*" Action: "Update:*" Resource: "*" - Effect: Deny Principal: "*" Resource: "*" Action: - Update:Replace - Update:Delete Condition: StringEquals: ResourceType: - AWS::EC2::Instance vpc: # Optional VPC. But if you use VPC then both subproperties (securityGroupIds and subnetIds) are required securityGroupIds: - securityGroupId1 - securityGroupId2 subnetIds: - subnetId1 - subnetId2 notificationArns: # List of existing Amazon SNS topics in the same region where notifications about stack events are sent. - 'arn:aws:sns:us-east-1:XXXXXX:mytopic' resourcePolicy: - Effect: Allow Principal: "*" Action: execute-api:Invoke Resource: - execute-api:/*/*/* Condition: IpAddress: aws:SourceIp: - "123.123.123.123" tags: # Optional service wide function tags foo: bar baz: qux tracing: apiGateway: true lambda: true # optional, can be true (true equals 'Active'), 'Active' or 'PassThrough' package: # Optional deployment packaging configuration include: # Specify the directories and files which should be included in the deployment package - src/** - handler.js exclude: # Specify the directories and files which should be excluded in the deployment package - .git/** - .travis.yml excludeDevDependencies: false # Config if Serverless should automatically exclude dev dependencies in the deployment package. Defaults to true artifact: path/to/my-artifact.zip # Own package that should be used. You must provide this file. individually: true # Enables individual packaging for each function. If true you must provide package for each function. Defaults to false functions: usersCreate: # A Function handler: users.create # The file and module for this specific function. name: ${self:provider.stage}-lambdaName # optional, Deployed Lambda name description: My function # The description of your function. memorySize: 512 # memorySize for this specific function. runtime: nodejs6.10 # Runtime for this specific function. Overrides the default which is set on the provider level timeout: 10 # Timeout for this specific function. Overrides the default set above. role: arn:aws:iam::XXXXXX:role/role # IAM role which will be used for this function onError: arn:aws:sns:us-east-1:XXXXXX:sns-topic # Optional SNS topic / SQS arn (Ref, Fn::GetAtt and Fn::ImportValue are supported as well) which will be used for the DeadLetterConfig awsKmsKeyArn: arn:aws:kms:us-east-1:XXXXXX:key/some-hash # Optional KMS key arn which will be used for encryption (overwrites the one defined on the service level) environment: # Function level environment variables functionEnvVar: 12345678 tags: # Function specific tags foo: bar vpc: # Optional VPC. But if you use VPC then both subproperties (securityGroupIds and subnetIds) are required securityGroupIds: - securityGroupId1 - securityGroupId2 subnetIds: - subnetId1 - subnetId2 package: include: # Specify the directories and files which should be included in the deployment package for this specific function. - src/** - handler.js exclude: # Specify the directories and files which should be excluded in the deployment package for this specific function. - .git/** - .travis.yml artifact: path/to/my-artifact.zip # Own package that should be use for this specific function. You must provide this file. individually: true # Enables individual packaging for specific function. If true you must provide package for each function. Defaults to false layers: # An optional list Lambda Layers to use - arn:aws:lambda:region:XXXXXX:layer:LayerName:Y # Layer Version ARN tracing: Active # optional, can be 'Active' or 'PassThrough' (overwrites the one defined on the provider level) events: # The Events that trigger this Function - http: # This creates an API Gateway HTTP endpoint which can be used to trigger this function. Learn more in "events/apigateway" path: users/create # Path for this endpoint method: get # HTTP method for this endpoint cors: true # Turn on CORS for this endpoint, but don't forget to return the right header in your response private: true # Requires clients to add API keys values in the `x-api-key` header of their request authorizer: # An AWS API Gateway custom authorizer function name: authorizerFunc # The name of the authorizer function (must be in this service) arn: xxx:xxx:Lambda-Name # Can be used instead of name to reference a function outside of service resultTtlInSeconds: 0 identitySource: method.request.header.Authorization identityValidationExpression: someRegex type: token # token or request. Determines input to the authorier function, called with the auth token or the entire request event. Defaults to token - websocket: route: $connect authorizer: # name: auth NOTE: you can either use "name" or arn" properties arn: arn:aws:lambda:us-east-1:1234567890:function:auth identitySource: - 'route.request.header.Auth' - 'route.request.querystring.Auth' - s3: bucket: photos event: s3:ObjectCreated:* rules: - prefix: uploads/ - suffix: .jpg - schedule: name: my scheduled event description: a description of my scheduled event's purpose rate: rate(10 minutes) enabled: false # Note, you can use only one of input, inputPath, or inputTransformer input: key1: value1 key2: value2 stageParams: stage: dev inputPath: '$.stageVariables' inputTransformer: inputPathsMap: eventTime: '$.time' inputTemplate: '{"time": , "key1": "value1"}' - sns: topicName: aggregate displayName: Data aggregation pipeline - sqs: arn: arn:aws:sqs:region:XXXXXX:myQueue batchSize: 10 - stream: arn: arn:aws:kinesis:region:XXXXXX:stream/foo batchSize: 100 startingPosition: LATEST enabled: false - alexaSkill: appId: amzn1.ask.skill.xx-xx-xx-xx enabled: true - alexaSmartHome: appId: amzn1.ask.skill.xx-xx-xx-xx enabled: true - iot: name: myIoTEvent description: An IoT event enabled: true sql: "SELECT * FROM 'some_topic'" sqlVersion: beta - cloudwatchEvent: event: source: - "aws.ec2" detail-type: - "EC2 Instance State-change Notification" detail: state: - pending # Note, you can use only one of input, inputPath, or inputTransformer input: key1: value1 key2: value2 stageParams: stage: dev inputPath: '$.stageVariables' inputTransformer: inputPathsMap: eventTime: '$.time' inputTemplate: '{"time": , "key1": "value1"}' - cloudwatchLog: logGroup: '/aws/lambda/hello' filter: '{$.userIdentity.type = Root}' - cognitoUserPool: pool: MyUserPool trigger: PreSignUp layers: hello: # A Lambda layer path: layer-dir # required, path to layer contents on disk name: ${self:provider.stage}-layerName # optional, Deployed Lambda layer name description: Description of what the lambda layer does # optional, Description to publish to AWS compatibleRuntimes: # optional, a list of runtimes this layer is compatible with - python3.7 licenseInfo: GPLv3 # optional, a string specifying license information allowedAccounts: # optional, a list of AWS account IDs allowed to access this layer. - '*' retain: false # optional, false by default. If true, layer versions are not deleted as new ones are created # The "Resources" your "Functions" use. Raw AWS CloudFormation goes in here. resources: Resources: usersTable: Type: AWS::DynamoDB::Table Properties: TableName: usersTable AttributeDefinitions: - AttributeName: email AttributeType: S KeySchema: - AttributeName: email KeyType: HASH ProvisionedThroughput: ReadCapacityUnits: 1 WriteCapacityUnits: 1 # The "Outputs" that your AWS CloudFormation Stack should produce. This allows references between services. Outputs: UsersTableArn: Description: The ARN for the User's Table Value: "Fn::GetAtt": [ usersTable, Arn ] Export: Name: ${self:service}:${opt:stage}:UsersTableArn # see Fn::ImportValue to use in other services and http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/outputs-section-structure.html for documentation on use. Terms Query string body mapping template ===================================== See https://forum.serverless.com/t/can-you-define-a-url-query-string-parameter-for-a-get-request/292/2 You need integration:lambda for this. :: functions: create: handler: posts.create events: - http: method: get path: whatever request: template: application/json: > { "foo" : "$input.params('foo')", "someData": "$input.params('some_data')" } Another example to set mandatory/optional query string parameters:: functions: create: handler: posts.create events: - http: method: get path: whatever request: parameters: querystrings: url: true Best Cors Reference ==================== See https://serverless.com/framework/docs/providers/aws/events/apigateway/ Setting cors to true assumes a default configuration which is equivalent to:: functions: hello: handler: handler.hello events: - http: path: hello method: get cors: origin: '*' headers: - Content-Type - X-Amz-Date - Authorization - X-Api-Key - X-Amz-Security-Token - X-Amz-User-Agent allowCredentials: false