UNPKG

serverless

Version:

Serverless Framework - Build web, mobile and IoT applications with serverless architectures using AWS Lambda, Azure Functions, Google CloudFunctions & more

569 lines (551 loc) 29.5 kB
<!-- title: Serverless Framework - AWS Lambda Guide - Serverless.yml Reference menuText: Serverless.yml menuOrder: 16 description: A list of all available properties on serverless.yml for AWS layout: Doc --> <!-- DOCS-SITE-LINK:START automatically generated --> ### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/guide/serverless.yml) <!-- DOCS-SITE-LINK:END --> # Serverless.yml Reference Here is a list of all available properties in `serverless.yml` when the provider is set to `aws`. ```yml # serverless.yml service: myService frameworkVersion: '2' enableLocalInstallationFallback: false # If set to 'true', guarantees that it's a locally (for service, in its node_modules) installed framework which processes the command useDotenv: false # If set to 'true', environment variables will be automatically loaded from .env files disabledDeprecations: # Disable deprecation logs by their codes. Default is empty. - DEP_CODE_1 # Deprecation code to disable - '*' # Disable all deprecation messages provider: name: aws runtime: nodejs12.x stage: dev # Default stage to be used. Default is "dev" region: us-east-1 # Default region to be 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 kmsKeyArn: arn:aws:kms:us-east-1:XXXXXX:key/some-hash # KMS key arn which will be used for encryption for all functions deploymentBucket: blockPublicAccess: true # Prevents public access via ACLs or bucket policies. Default is false skipPolicySetup: false # Prevents creation of default bucket policy when framework creates the deployment bucket. Default is false name: com.serverless.${self:provider.region}.deploys # Deployment bucket name. Default is generated by the framework maxPreviousDeploymentArtifacts: 10 # On every deployment the framework prunes the bucket to remove artifacts older than this limit. The default is 5 serverSideEncryption: AES256 # server-side encryption method sseKMSKeyId: arn:aws:kms:us-east-1:xxxxxxxxxxxx:key/aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa # when using server-side encryption sseCustomerAlgorithim: AES256 # when using server-side encryption and custom keys sseCustomerKey: string # when using server-side encryption and custom keys sseCustomerKeyMD5: md5sum # when using server-side encryption and custom keys 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 rolePermissionsBoundary: arn:aws:iam::XXXXXX:policy/policy # ARN of an Permissions Boundary for the role. lambdaHashingVersion: 20201221 # optional, version of hashing algorithm that should be used by the framework cfnRole: arn:aws:iam::XXXXXX:role/role # ARN of an IAM role for CloudFormation service. If specified, CloudFormation uses the role's credentials cloudFront: myCachePolicy1: # used as a reference in function.events[].cloudfront.cachePolicy.name DefaultTTL: 60 MinTTL: 30 MaxTTL: 3600 Comment: my brand new cloudfront cache policy # optional ParametersInCacheKeyAndForwardedToOrigin: CookiesConfig: CookieBehavior: whitelist # Possible values are 'none', 'whitelist', 'allExcept' and 'all' Cookies: - my-public-cookie EnableAcceptEncodingBrotli: true # optional EnableAcceptEncodingGzip: true HeadersConfig: HeadersBehavior: whitelist # Possible values are 'none' and 'whitelist' Headers: - authorization - content-type QueryStringsConfig: QueryStringBehavior: allExcept # Possible values are 'none', 'whitelist', 'allExcept' and 'all' QueryStrings: - not-cached-query-string 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. 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 websocketApiId: # Websocket API resource ID. Default is generated by the framework apiKeySourceType: HEADER # Source of API key for usage plan. HEADER or AUTHORIZER. apiKeys: # List of API keys to be used by your service API Gateway REST API - myFirstKey value: myFirstKeyValue description: myFirstKeyDescription customerId: myFirstKeyCustomerId - ${opt:stage}-myFirstKey - ${env:MY_API_KEY} # you can hide it in a serverless variable 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 binaryMediaTypes: # Optional binary media types the API might return - '*/*' metrics: false # Optional detailed Cloud Watch Metrics shouldStartNameWithService: false # Use `${service}-${stage}` naming for API Gateway. Will be `true` by default in next major version. resourcePolicy: - Effect: Allow Principal: '*' Action: execute-api:Invoke Resource: - execute-api:/*/*/* Condition: IpAddress: aws:SourceIp: - '123.123.123.123' usagePlan: # Optional usage plan configuration quota: limit: 5000 offset: 2 period: MONTH throttle: burstLimit: 200 rateLimit: 100 alb: targetGroupPrefix: xxxxxxxxxx # Optional prefix to prepend when generating names for target groups authorizers: myFirstAuth: type: 'cognito' userPoolArn: 'arn:aws:cognito-idp:us-east-1:123412341234:userpool/us-east-1_123412341', # required userPoolClientId: '1h57kf5cpq17m0eml12EXAMPLE', # required userPoolDomain: 'your-test-domain' # required onUnauthenticatedRequest: 'deny' # If set to 'allow' this allows the request to be forwarded to the target when user is not authenticated. When omitted it defaults 'deny' which makes a HTTP 401 Unauthorized error be returned. Alternatively configure to 'authenticate' to redirect request to IdP authorization endpoint. requestExtraParams: # optional. The query parameters (up to 10) to include in the redirect request to the authorization endpoint prompt: 'login' redirect: false scope: 'first_name age' # Can be a combination of any system-reserved scopes or custom scopes associated with the client. The default is openid sessionCookieName: '🍪' # The name of the cookie used to maintain session information. The default is AWSELBAuthSessionCookie sessionTimeout: 7000 # The maximum duration of the authentication session, in seconds. The default is 604800 seconds (7 days). mySecondAuth: type: 'oidc' authorizationEndpoint: 'https://example.com', # required. The authorization endpoint of the IdP. Must be a full URL, including the HTTPS protocol, the domain, and the path clientId: 'i-am-client', # required clientSecret: 'i-am-secret', # if creating a rule this is required. If modifying a rule, this can be omitted if you set useExistingClientSecret to true (as below) useExistingClientSecret: true # only required if clientSecret is omitted issuer: 'https://www.iamscam.com', # required. The OIDC issuer identifier of the IdP. This must be a full URL, including the HTTPS protocol, the domain, and the path tokenEndpoint: 'http://somewhere.org', # required userInfoEndpoint: 'https://another-example.com' # required onUnauthenticatedRequest: 'deny' # If set to 'allow' this allows the request to be forwarded to the target when user is not authenticated. Omit or set to 'deny' (default) to make a HTTP 401 Unauthorized error be returned instead. Alternatively configure to 'authenticate' to redirect request to IdP authorization endpoint. requestExtraParams: prompt: 'login' redirect: false scope: 'first_name age' sessionCookieName: '🍪' sessionTimeout: 7000 httpApi: id: 'my-id' # If we want to attach to externally created HTTP API its id should be provided here name: 'dev-my-service' # Use custom name for the API Gateway API, default is ${opt:stage, self:provider.stage, 'dev'}-${self:service} payload: '1.0' # Specify payload format version for Lambda integration ('1.0' or '2.0'), default is '1.0' cors: true # Implies default behavior, can be fine tuned with specficic options authorizers: # JWT authorizers to back HTTP API endpoints someJwtAuthorizer: identitySource: $request.header.Authorization issuerUrl: https://cognito-idp.us-east-1.amazonaws.com/us-east-1_xxxxx audience: - xxxx - xxxx 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' stackParameters: - ParameterKey: 'Keyname' ParameterValue: 'Value' rollbackConfiguration: MonitoringTimeInMinutes: 20 RollbackTriggers: - Arn: arn:aws:cloudwatch:us-east-1:000000000000:alarm:health Type: AWS::CloudWatch::Alarm - Arn: arn:aws:cloudwatch:us-east-1:000000000000:alarm:latency Type: AWS::CloudWatch::Alarm 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' logs: restApi: # Optional configuration which specifies if API Gateway logs are used. This can either be set to `true` to use defaults, or configured via subproperties. accessLogging: true # Optional configuration which enables or disables access logging. Defaults to true. format: 'requestId: $context.requestId' # Optional configuration which specifies the log format to use for access logging. executionLogging: true # Optional configuration which enables or disables execution logging. Defaults to true. level: INFO # Optional configuration which specifies the log level to use for execution logging. May be set to either INFO or ERROR. fullExecutionData: true # Optional configuration which specifies whether or not to log full requests/responses for execution logging. Defaults to true. role: arn:aws:iam::123456:role # Existing IAM role for ApiGateway to use when managing CloudWatch Logs. If 'role' is not configured, a new role is automatically created. roleManagedExternally: false # Specifies whether the ApiGateway CloudWatch Logs role setting is not managed by Serverless. Defaults to false. websocket: # Optional configuration which specifies if Websocket logs are used. This can either be set to `true` to use defaults, or configured via subproperties. level: INFO # Optional configuration which specifies the log level to use for execution logging. May be set to either INFO or ERROR. httpApi: # Optional configuration which specifies if HTTP API logs are used. This can either be set to `true` (to use defaults as below) or specific log format configuration can be provided format: '{ "requestId":"$context.requestId", "ip": "$context.identity.sourceIp", "requestTime":"$context.requestTime", "httpMethod":"$context.httpMethod","routeKey":"$context.routeKey", "status":"$context.status","protocol":"$context.protocol", "responseLength":"$context.responseLength" }' frameworkLambda: true # Optional, whether to write CloudWatch logs for custom resource lambdas as added by the framework 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: ${opt:stage, self:provider.stage, 'dev'}-lambdaName # optional, Deployed Lambda name description: My function # The description of your function. memorySize: 512 # memorySize for this specific function. reservedConcurrency: 5 # optional, reserved concurrency limit for this function. By default, AWS uses account concurrency limit provisionedConcurrency: 3 # optional, Count of provisioned lambda instances runtime: nodejs12.x # 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 kmsKeyArn: 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 provider level) disableLogs: false # Disables creation of CloudWatch Log Group 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) condition: SomeCondition # optional, adds 'Condition' clause dependsOn: # optional, appends these additional resources to the 'DependsOn' list - MyThing - MyOtherThing destinations: # optional, destinations for async invocations onSuccess: functionName # function name or ARN of a target (externally managed lambda, EventBridge event bus, SQS queue or SNS topic) onFailure: xxx:xxx:target # function name or ARN of a target (externally managed lambda, EventBridge event bus, SQS queue or SNS topic) fileSystemConfig: arn: arn:aws:elasticfilesystem:us-east-1:111111111111:access-point/fsap-a1a1a1a1a1a1a1a1a # ARN of EFS Access Point localMountPath: /mnt/example # path under which EFS will be mounted and accessible by Lambda function 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 authorizer function, called with the auth token or the entire request event. Defaults to token request: # configure method request and integration request settings uri: http://url/{paramName} # Define http endpoint URL and map path parameters for HTTP and HTTP_PROXY requests parameters: # Optional request parameter configuration paths: paramName: true # mark path parameter as required headers: headerName: true # mark header required custom-header: # Optional add a new header to the request required: true mappedValue: context.requestId # map the header to a static value or integration request variable querystrings: paramName: true # mark query string schema: # Optional request schema validation; mapped by content type application/json: ${file(create_request.json)} # define the valid JSON Schema for a content-type template: # Optional custom request mapping templates that overwrite default templates application/json: '{ "httpMethod" : "$context.httpMethod" }' passThrough: NEVER # Optional define pass through behavior when content-type does not match any of the specified mapping templates - httpApi: # HTTP API endpoint method: GET path: /some-get-path/{param} authorizer: # Optional name: someJwtAuthorizer # References by name authorizer defined in provider.httpApi.authorizers section scopes: # Optional - user.id - user.email - websocket: route: $connect routeResponseSelectionExpression: $default # optional, setting this enables callbacks on websocket requests for two-way communication 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 existing: true # optional, if you're using an existing Bucket - 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": <eventTime>, "key1": "value1"}' - sns: topicName: aggregate displayName: Data aggregation pipeline filterPolicy: pet: - dog - cat redrivePolicy: # (1) ARN deadLetterTargetArn: arn:aws:sqs:us-east-1:11111111111:myDLQ # (2) Ref (resource defined in same CF stack) deadLetterTargetRef: myDLQ # (3) Import (resource defined in outer CF stack) deadLetterTargetImport: arn: MyShared-DLQArn url: MyShared-DLQUrl - sqs: arn: arn:aws:sqs:region:XXXXXX:myQueue batchSize: 10 enabled: true - stream: arn: arn:aws:kinesis:region:XXXXXX:stream/foo batchSize: 100 maximumRecordAgeInSeconds: 120 startingPosition: LATEST enabled: true - msk: arn: arn:aws:kafka:us-east-1:111111111111:cluster/ClusterName/a1a1a1a1a1a1a1a1a # ARN of MSK Cluster topic: kafkaTopic # name of Kafka topic to consume from batchSize: 100 # optional, must be in 1-10000 range startingPosition: LATEST # optional, can be set to LATEST or TRIM_HORIZON enabled: true # optional, true by default, can be used to disable event without deleting resource - 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": <eventTime>, "key1": "value1"}' - cloudwatchLog: logGroup: '/aws/lambda/hello' filter: '{$.userIdentity.type = Root}' - cognitoUserPool: pool: MyUserPool trigger: PreSignUp existing: true # optional, if you're referencing an existing User Pool - alb: listenerArn: arn:aws:elasticloadbalancing:us-east-1:12345:listener/app/my-load-balancer/50dc6c495c0c9188/ priority: 1 conditions: host: example.com path: /hello healthCheck: # optional, can also be set using a boolean value path: / # optional intervalSeconds: 35 # optional timeoutSeconds: 30 # optional healthyThresholdCount: 5 # optional unhealthyThresholdCount: 5 # optional matcher: # optional httpCode: '200' - eventBridge: # using the default AWS event bus schedule: rate(10 minutes) # creating an event bus eventBus: custom-saas-events pattern: source: - saas.external # re-using an existing event bus eventBus: arn:aws:events:us-east-1:12345:event-bus/custom-private-events pattern: source: - custom.private inputTransformer: inputPathsMap: eventTime: '$.time' inputTemplate: '{"time": <eventTime>, "key1": "value1"}' # using `inputs` pattern: source: - 'aws.ec2' detail-type: - 'EC2 Instance State-change Notification' detail: state: - pending input: key1: value1 key2: value2 stageParams: stage: dev # using `inputPath` pattern: source: - 'aws.ec2' detail-type: - 'EC2 Instance State-change Notification' detail: state: - pending inputPath: '$.stageVariables' # using `inputTransformer` pattern: source: - 'aws.ec2' detail-type: - 'EC2 Instance State-change Notification' detail: state: - pending inputTransformer: inputPathsMap: eventTime: '$.time' inputTemplate: '{"time": <eventTime>, "key1": "value1"}' - cloudFront: eventType: viewer-response includeBody: true pathPattern: /docs* cachePolicy: # Note, you can use only one of name or id name: myCachePolicy1 # Refers to a Cache Policy defined in provider.cloudFront.cachePolicies id: 658327ea-f89d-4fab-a63d-7e88639e58f6 # Refers to any external Cache Policy id origin: DomainName: serverless.com OriginPath: /framework CustomOriginConfig: OriginProtocolPolicy: match-viewer configValidationMode: warn # Modes for config validation. `error` throws an exception, `warn` logs error to console, `off` disables validation at all. The default is warn. layers: hello: # A Lambda layer path: layer-dir # required, path to layer contents on disk name: ${opt:stage, self:provider.stage, 'dev'}-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.8 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 extensions: # override Properties or other attributes of Framework-created resources. # See https://serverless.com/framework/docs/providers/aws/guide/resources#override-aws-cloudformation-resource for more details UsersCreateLogGroup: Properties: RetentionInDays: '30' # 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. ```