Giter VIP home page Giter VIP logo

aws / serverless-application-model Goto Github PK

View Code? Open in Web Editor NEW
9.2K 286.0 2.4K 118.86 MB

The AWS Serverless Application Model (AWS SAM) transform is a AWS CloudFormation macro that transforms SAM templates into CloudFormation templates.

Home Page: https://aws.amazon.com/serverless/sam

License: Apache License 2.0

Makefile 0.19% Python 99.73% Shell 0.08%
serverless aws lambda aws-sam sam sam-specification serverless-applications serverless-application-model

serverless-application-model's Introduction

AWS SAM transform

Tests Update schema PyPI PyPI - Python Version Contribute with Gitpod

The AWS Serverless Application Model (AWS SAM) transform is a AWS CloudFormation macro that transforms SAM templates into CloudFormation templates.

To use the SAM transform, add AWS::Serverless-2016-10-31 to the Transform section of your CloudFormation template.

Benefits of using the SAM transform include:

  • Built-in best practices and sane defaults.
  • Local testing and debugging with the AWS SAM CLI.
  • Extension of the CloudFormation template syntax.

Getting started

Save the following as template.yaml:

Transform: AWS::Serverless-2016-10-31
Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      Runtime: nodejs18.x
      Handler: index.handler
      InlineCode: |
        exports.handler = async (event) => {
          console.log(event);
        }

And deploy it with the SAM CLI:

sam sync --stack-name sam-app

The AWS::Serverless::Function resource will create a AWS Lambda function that logs events it receives.

Under the hood, the template is transformed into the JSON equivalent of the following CloudFormation template:

Resources:
  MyFunction:
    Type: AWS::Lambda::Function
    Properties:
      Code:
        ZipFile: |
          exports.handler = async (event) => {
            console.log(event);
          }
      Handler: index.handler
      Role: !GetAtt MyFunctionRole.Arn
      Runtime: nodejs18.x
      Tags:
        - Key: lambda:createdBy
          Value: SAM
  MyFunctionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Action:
              - sts:AssumeRole
            Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
      Tags:
        - Key: lambda:createdBy
          Value: SAM

For a more thorough introduction, see the this tutorial in the Developer Guide.

Contributing

Setting up development environment

You'll need to have Python 3.8+ installed.

Create a virtual environment:

python3 -m venv .venv
source .venv/bin/activate

Set up dependencies:

make init

Run tests:

make pr

See DEVELOPMENT_GUIDE.md for further development instructions, and CONTRIBUTING.md for the contributing guidelines.

Getting help

The best way to interact with the team is through GitHub. You can either create an issue or start a discussion.

You can also join the #samdev channel on Slack.

Learn more

Workshops and tutorials

Documentation

serverless-application-model's People

Contributors

53ningen avatar aahung avatar aaythapa avatar acristin avatar awood45 avatar aws-sam-cli-bot avatar brettstack avatar connorrobertson avatar coshus avatar dependabot[bot] avatar gavinzz avatar github-actions[bot] avatar gracelu0 avatar hawflau avatar hoffa avatar jfuss avatar jlhood avatar keetonian avatar mgrandis avatar mildaniel avatar mingkun2020 avatar mndeveci avatar moelasmar avatar praneetap avatar qingchm avatar sanathkr avatar ssenchenko avatar torresxb1 avatar wchengru avatar xazhao avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

serverless-application-model's Issues

S3 Event Source Mapping: Could not list s3 event sources.

Hi Guys,

I was evaluating SAM and created a stack with the YAML below. The stack creates fine, but if I view the Lambda function triggers, I only see an error: Could not list s3 event sources.

If I inspect this function via the API, no even sources are mapped to the function. Is this a problem with my YAML, or a bug?

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: A function is triggered off an upload to a bucket. It logs the content type of the uploaded object.
Resources:
  ProcessorFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.handler
      Runtime: nodejs4.3
      CodeUri: s3://<mybucket>/HelloWorldNode.zip
      Policies: AmazonS3ReadOnlyAccess
      Events:
        Addition:
          Type: S3
          Properties:
            Bucket: !Ref Bucket
            Events: s3:ObjectCreated:*

  Bucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: sam-cfn-test

Support CloudFormation intrinsic functions in SAM resources

We quite often use !Ref, !Sub, !Join in properties that are supposed to hold strings such as CodeUri, DefinitionUri, StageName (#19) etc. This is a perfectly valid CloudFormation, but the transformation logic that parses SAM does not resolve intrinsic functions before parsing the property as a string. So the transformation logic would fail and depending on the property it could either return a validation error or internal failure. Properties that are directly passed down to CloudFormation are unaffected by this problem.

This is a feature request to add support for resolving a subset of CloudFormation intrinsics in the transformation logic. We care about only the subset of properties that the transform manipulates, like CodeUri.

Following intrinsics will be supported:

  • !Sub
  • !Join

on following properties:

  • CodeUri on AWS::Serverless::Function
  • Role on AWS::Serverless::Function
  • DefinitionUri on AWS::Serverless::Api
  • StageName on AWS::Serverless::Api

Custom Domain Names?

Is there a way in SAM to define your Custom Domain Name for an API Gateway endpoint, as well as the base path for it?

Code pipline failed due to: No integration defined for method

Hi,
My Code Pipline fails. inthe execution phase with the following error:

Execute
AWS CloudFormation
Failed 18 hours ago Details

Action execution failed
Failed to execute change set. Current stack status: UPDATE_ROLLBACK_COMPLETE. Reason: No reason was provided.
Link to execution details

Clicking on details shifts to cloud formation stack with the following errors:

13:58:37 UTC+0200 UPDATE_ROLLBACK_IN_PROGRESS AWS::CloudFormation::Stack ProdStack2 The following resource(s) failed to create: [apiDeployment].
13:58:35 UTC+0200 CREATE_FAILED AWS::ApiGateway::Deployment apiDeployment No integration defined for method
13:58:34 UTC+0200 CREATE_IN_PROGRESS AWS::ApiGateway::Deployment apiDeployment

Pay attention running the following command locally succeeded:
aws cloudformation deploy --template-file c:\StackData\lambda\outputTemplate.yml --stack-name ProdStack --capabilities CAPABILITY_IAM `

My Template file is:

AWSTemplateFormatVersion: '2010-09-09'
Description: Outputs the time
Resources:
  f1:
    Properties:
      CodeUri: s3://lambdabiot/6135bb77878b4c847aee2b609cef4cc2
      Events:
        MyApi:
          Properties:
            Method: GET
            Path: /f1
          Type: Api
      Handler: index.handler
      Runtime: nodejs4.3
    Type: AWS::Serverless::Function
  f2:
    Properties:
      CodeUri: s3://lambdabiot/86bd36e690b8f6a2ee59e9375ed7b983
      Events:
        MyApi:
          Properties:
            Method: GET
            Path: /f2
          Type: Api
      Handler: index.handler
      Runtime: nodejs4.3
    Type: AWS::Serverless::Function
Transform: AWS::Serverless-2016-10-31

Question: multiple environments, different properties

So I've seen the stage variables and environment variables but I'm not sure if thats what I need.

What's the correct way to execute the same template in each environment but swap out things like proxy urls, AuthorizationType user pool IDs, etc?

Currently I just use two completely different sam.yaml files that define different stage variables & point to separate stages. Both YAML files point to the same API gateway swagger definition file. Is there a better way?

Consider adding default Runtime for all Functions

Currently, we have to explicitly set Runtime property for each Function resource, which makes the template unnecessarily verbose. Since most functions will likely be located in the same file (at least for a single resource) or a set of dependent modules, we can assume they will all run under the same runtime. Moreover, it would be nice to avoid hard-coding the runtime version into the template and specify it as a parameter instead:

Parameters:
  Runtime:
    Type: String
    Default: nodejs4.3
    AllowedValues:
      - nodejs
      - nodejs4.3
      - java8
      - python2.7
    ...

or even perhaps

Parameters:
  Runtime:
    Type: AWS::Lambda::Function::Runtime
    Default: nodejs4.3
    ...

for an ultimate conciseness. Or even better (though partisan), define nodejs4.3 as the default value of Runtime in the spec. In the latter case, one should still be able to easily specify a different global runtime using syntax similar to the above. Needless to say, in all cases if any function still requires its own runtime, we would still be able to override the global default using the current syntax.

VpcConfig leaves behind Network Interface

When I create a stack that uses the VpcConfig (hard coded due to #22) and then go to delete the stack the resulting ENI that is created to enable the VpcConfig isn't deleted so when I go to delete the database and it's security group, the security group cannot be deleted due to the lingering lambda function's ENI.

As a user, when I delete a AWS::Serverless::Function with a VpcConfig specified the ENI should be deleted as well.

Encrypt Variables

Hey! Awesome job by the way. I really love using this. There are a TON of things that this can give us that I don't have to build.

But I have a feature request (if it isn't already done)

With the cloudformation, can you specify encrypted? That way, when we use 'aws cloudformation deploy' it will go through, and encrypt with the KMS key you specify?

Something like this maybe

Environment:
  KmsKeyId: 1234-1234-1234-1234
  Variables:
    NON_SECRET: blah
    SECRET: !Encrypt this_gets_encrypted

Then we can just do the regular boto.kms.decrypt when we need to decrypt it in the lambda.

Question on api_swagger_cors example

After replacing <> and <>, I successfully created a stack for this example along with lambda invoke permissions, but when I test the api methods, it fails with a permission error even if I specify the lambda function name in 'Stage Variables -LambdaFunctionName'.

So I changed the target lambda function name from '${stageVariables.LambdaFunctionName}' to the real function name in the 'Integration Request' section and it works ok, but I don't think it is necessary.

So I'm wondering if I'm missing something.

stageVariables in Swagger are not expanded

When trying the serverless-application-model/examples/2016-10-31/api_swagger_cors/ example, the Lambda function name is not expanded.

I edited the swagger.yaml to add Role: to the Lambda as it's required in my environment. and then did packaging and deploying.

I went to the API Gateway console for Method Execution / ANY - Integration Request.
In the Lambda Function value,

Expected: the name of the Lambda function, dynamically assigned.
Got: ${stageVariables.LambdaFunctionName}

This happened when I was testing #20, after #20 (comment)

SNS topic to being linked to Function?

Can I use !Ref to reference an SNS topic defined in the same template? The following pseudo-code is basically what I'm trying to achieve. The function and topic gets created but the function does not have a trigger for the SNS topic automatically created.

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.handler
      Runtime: nodejs4.3
      Timeout: 10
    Events:
      MyTopic:
        Type: SNS
        Properties:
          Topic: !Ref ExampleTopic
  ExampleTopic:
    Type: "AWS::SNS::Topic"
    Properties:
      DisplayName: example

VpcConfig invalid when referencing other resources

The following returns the error message Resource with id [SampleFunction] is invalid. Type of property 'VpcConfig' is invalid. though appears to be valid.

VpcConfig:
  SecurityGroupIds:
    - !Ref FunctionSecurityGroup
  SubnetIds:
    - !ImportValue "aroundme-private-subnet"

When I modify the block to reference the actual values (as follows), template works as expected, thus this seems to be a transform issue.

VpcConfig:
  SecurityGroupIds:
    - "sg-ABC123"
  SubnetIds:
    - "subnet-ABC123"

Accept a FunctionName parameter for AWS::Serverless::Function

I'd like to be able to specify my own function name. In my template I receive the stage name as a parameter and I'd like to generate a function name such as "myfunction_${Stage}" -> "myfunction_dev".

This will make it easier for the on-call to find the function/logs that's causing the errors.

Inject StageVariable into API resource definition that uses a Swagger file

When using a Swagger file to define an API, users have to explicitly specify Stage Variables to hold the Lambda function ARN and use the stage variable in their Swagger template to specify the integration. This is not intuitive.

We could simplify this process by automatically injecting the Stage Variable when users specify an API Event source to their Lambda Function

When customers specify a template like this:

LambdaFunction:
  Type: AWS::Serverless::Function
  Properties:
      Handler: index.handler
      Runtime: nodejs4.3
      Events:
         GetApi:
             Type: API
              Properties:
                  Path: /
                  Method: GET
                  RestApiId: !Ref MyApiResource

MyApiResource:
   Type: AWS::Serverless::Api
   Properties:
        DefinitionUri: s3://bucket/myswagger.yaml

we could inject a StageVariable to the API resource where variable name is equal to the function resource's logical name and value equal to the function's ARN

MyApiResource:
   Type: AWS::Serverless::Api
   Properties:
        DefinitionUri: s3://bucket/myswagger.yaml
        Variables:
             LambdaFunction: !Ref LambdaFunction

CodeCommit event support?

Hi Team,

It'd be really nice to trigger a function based on CodeCommit events, which is already supported by Lambda. It looks like all that's needed is a new event source type in SAM that implements that call.

Thanks

Internal transform failure for StageName defined by reference in a SAM template

Hi, I'm trying to create a simple stack for SAM that references a Swagger file using this configuration:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Parameters:
  APIStage:
    Default: dev
    Description: Name of the API stage to use for deployment
    Type: String
    AllowedPattern: '[A-Za-z0-9-]*'

Resources:
  Api:
    Type: AWS::Serverless::Api
    Properties:
      StageName: !Ref APIStage
      DefinitionUri: models.yaml

However,

aws cloudformation package --template-file sam.yaml --output-template-file deploy.yaml --s3-bucket backend-dev-xxxx
aws cloudformation deploy --template-file deploy.yaml --stack-name backend-dev --capabilities CAPABILITY_IAM --parameter-overrides APIStage=dev

leads to

Failed to create the changeset: Waiter ChangeSetCreateComplete failed: Waiter encountered a terminal failure state Status: FAILED. Reason: Transform AWS::Serverless-2016-10-31 failed with: Internal transform failure.

When I remove the Parameters section and set StageName: dev explicitly, the stack is created successfully. So it seems like Transform fails because of the APIStage reference, even though the template is validated successfully before CloudFormation calls Transform.

Open source

I'd like to request making the underlying implementation of the Serverless Application Model available under the same LICENSE that governs the specification distributed in this repository.

This would help users by giving them the ability to inspect the underlying implementation to help with debugging unexpected behavior and edge-cases. It would help the project by making it possible for external contributors interested in supporting and advancing this project to submit pull requests with bug and documentation fixes, new tests and feature implementations, etc.

Live logging of stack creation process?

Hi team,

I'm not sure if this question belongs here, but would it be possible to enable colorized logging of stack creation messages via the CLI while running aws cloudformation deploy ...? I know we can retrieve them after the fact using aws cloudformation describe-stack-events ..., but it would be nice to match similar functionality from the Serverless framework. Currently, I find myself opening a separate browser tab to watch progress of stack formation, even though the short summary of the progress is already being output in the CLI:

Waiting for changeset to be created..
Waiting for stack create/update to complete

Failed to create/update the stack. Run the following command
to fetch the list of events leading up to the failure
aws cloudformation describe-stack-events --stack-name stack-name

These messages don't tell us much, and ask us to perform a separate action even though they could just do so themselves. Since stack rollback usually takes a while, I'd prefer to notice any error messages in color (e.g. red) and as they appear, and start fixing them right away, instead of waiting for the console to return with the generic message (or relying on a separate tab just for that).

Thanks

Requires capabilities : [CAPABILITY_IAM]

Hi,
I am trying to enable serverless deployment with pipline and cloudformation services but failing to do so due to the following error:

My set of commands was:

c:\StackData\lambda>aws cloudformation package --template-file samTemplate.yml --s3-bucket lambdabiot --output-template-file outputTemplate.yml

Successfully packaged artifacts and wrote output template to file outputTemplate.yml.
Execute the following command to deploy the packaged template
aws cloudformation deploy --template-file c:\StackData\lambda\outputTemplate.yml --stack-name <YOUR STACK NAME>

c:\StackData\lambda>
c:\StackData\lambda>aws cloudformation deploy --template-file c:\StackData\lambda\outputTemplate.yml --stack-name ProdStack
Waiting for changeset to be created..

An error occurred (InsufficientCapabilitiesException) when calling the ExecuteChangeSet operation: Requires capabilities : [CAPABILITY_IAM]

Questions about Deployment using SAM

Hello,

I have just successfully used SAM to deploy serverless express application(lambda + apigateway) across accounts. Couple things I have questions about:

  • I noticed that if I update my swagger file it does not deploy the changes. Is this because my swagger file s3 path and name have not changed? I am hard coding it into the template and not using the automatic uri that the package command can offer.

  • Is there a good way to enable cloud watch logs via the api resouce.

I will have lots of questions :)

Braun

Cannot add multiple reference variables to AWS::Serverless::Api

When adding a AWS::Serverless::Api specifying multiple reference variables causes the message "Number of errors found: 1. Resource with id [TestUploadtestStage] is invalid. Type of property 'Variables' is invalid." when deploying with "aws cloudformation deploy".
I can add either of the variables but cannot add both

  TestUpload:
     Type: AWS::Serverless::Api
     Properties:
        StageName: test
        DefinitionUri: swagger.json
        Variables:
          DeleteFunctionArn: !Ref DeleteFunction
          PutFunctionArn: !Ref PutFunction

Have I just got the syntax incorrect?

Providing a parameter gives an error.

Had some trouble finding info on this, but I'm getting a validation error, when I supply a Parameter to the SAM template:

aws cloudformation deploy --template-file template.yaml --stack-name stack2 --capabilities CAPABILITY_IAM

An error occurred (ValidationError) when calling the CreateChangeSet operation: Cannot specify UsePreviousValue on Parameters when ChangeSetType is CREATE

When I comment the Parameters, it creates fine.

Example code;

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
AWS SAM template with API defined for Application. Swagger yaml included for API
Parameters:
EnvParameter:
Type: String
Default: prod
Description: Enter string for environment label of this deployment stack.

*I currently have no references to the parameter in my template for testing.

No documented stage return value from AWS::Serverless::Api

The event source Api states that RestApiStage
"Typically, this is set to the stage name attribute of an AWS::Serverless::Api resource defined in this template."
yet the AWS::Serverless::Api does not have any, at least documented, stage return attribute.

Issue with Lambda-Permission for API-Gateway

All,

it seems to me that there is a bug with the created LAMBDA-Policy when creating a "ANY"- API-Gateway-Mapping to a Lambda-Function, see the template here:

app_spec.txt

The created Lambda policy includes (for Resource analytics the following condition), and therefore a Lambda permission Error occurs when testing the API-Gateway:

"Condition":{"ArnLike":{"AWS:SourceArn":"arn:aws:execute-api:us-east-1:310073746091:yi1i6eckj4/*/ANY/analytics/*"}}

instead of (resource manual has been created manually afterwards via API-Gateway-Gui):

"Condition":{"ArnLike":{"AWS:SourceArn":"arn:aws:execute-api:us-east-1:310073746091:yi1i6eckj4/*/*/manual/*"}}

Any Idea?

Best Regards,

Gregor
[email protected]

No integration defined for method when using Swagger

It complains about "No integration defined for method" when trying to use the transformation with Swagger file defined at AWS::Serverless::Api. Maybe we are trying it the wrong way but the idea was to have a swagger file with CORS definitions as well but with no x-amazon-apigateway-integration defined on the actual resource because we want CF to inject it using the Events property. A swagger file example would help us here.

Thanks!

cloudformation deploy exits without useful message

After running the aws cloudformation package command, I then run deploy and get this:

aws cloudformation deploy --template-file new_template.yml --stack-name stack_name --capabilities CAPABILITY_IAM --profile profile_name
Waiting for changeset to be created..

'Status'

It exits at that point. It gets stuck on the first event:
"ResourceStatus": "REVIEW_IN_PROGRESS",

I am using the code from this example:
https://github.com/awslabs/serverless-application-model/tree/master/examples/2016-10-31/hello_world

aws-cli/1.11.36 Python/2.7.10 Darwin/16.3.0 botocore/1.4.93

Internal transform failure

Hi,

I've tried to deploy a simple application with a lambda that reacts to a scheduled event:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Resources:
MySimpleFunction:
Type: AWS::Serverless::Function
Properties:
Handler: example.my_handler
Runtime: Python 2.7
CodeUri: s3://my-bucket/lambda-zips/myzip.zip
Role: arn:aws:iam::...:role/lambdaAccess
Events:
MyUploadEvent:
Type: Schedule
Properties:
Schedule: cron(45 10 ? * MON-FRI *)
Events: {"example": "hello world" }

The code itself is one of another test project & works, the codeuri should be valid (zip is in the specified location).

But when I run the aws cloudformation deploy command, I receive an error:

Failed to create the changeset: Waiter ChangeSetCreateComplete failed: Waiter encountered a terminal failure state Status: FAILED. Reason: Transform AWS::Serverless-2016-10-31 failed with: Internal transform failure.

The stack itself is stuck in "review in progress" and does not contain any additional information. Not sure if this is an issue on my side or in the serverless-application-model (though more detailed information than "internal transform failure" would be handy ;)).

Thanks!

How to add versioning to continuous deployment model

Hi,

Uncertain where best to propose this question, but this seems like a good place to start. I've been playing with automatically deploying lambda functions using this serverless application model + cloudformation, based off this document [1]. One thing I've noticed is that with every change set that code pipeline creates in cloudformation, I don't get a new version of the lambda function. How do you propose I add some kind of versioning (perhaps correlated with the CodeUri) to the cloudformation change set?

I appreciate your input on the matter.

[1] http://docs.aws.amazon.com/lambda/latest/dg/automating-deployment.html

How to setup body transformation?

Hi,

There are not many example out in the Internet yet. I tried to use this transformation for my existing serverless App where I return html and json in different API+lambda combinations and I use body transformations for requests and responses.

How can I specify these things with this transformation?

template resource

One of the downsides of the micro services architecture model is that there is more overhead because the configuration, management and deployment tasks are duplicated for each service. Our swagger schemas and Cloudformation templates are full of copy-and-pasted snippets.

In the example below, the commonality is extracted into LambdaTemplate, reducing the PutFunction to 3 lines and allowing the differences between the other functions to be more obvious.

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
  LambdaTemplate:
    Type: AWS::Serverless::TemplateFunction
    Properties:
      Handler: index.handler
      Runtime: nodejs4.3
      Policies: AWSLambdaDynamoDBExecutionRole
      CodeUri: s3://bucketName/codepackage.zip
      Environment:
        Variables:
          TABLE_NAME: !Ref Table

  PutFunction:
    Type: AWS::Serverless::Function
    Properties:
      # extra points if this can (optionally) be imported from an external file, even in a separate but shared repository
      Template: !Ref LambdaTemplate
  GetFunction:
    Type: AWS::Serverless::Function
    Properties:
      Template: !Ref LambdaTemplate
      Handler: index.getHandler
  DeleteFunction:
    Type: AWS::Serverless::Function
    Properties:
      Template: !Ref LambdaTemplate
      Events:
        Stream:
          Type: DynamoDB
          Properties:
            Stream: !GetAtt DynamoDBTable.StreamArn
            BatchSize: 100
            StartingPosition: TRIM_HORIZON

   DynamoDBTable:
     Type: AWS::DynamoDB::Table
     Properties: 
       AttributeDefinitions: 
         - AttributeName: id
           AttributeType: S
       KeySchema: 
         - AttributeName: id
           KeyType: HASH
       ProvisionedThroughput: 
         ReadCapacityUnits: 5
         WriteCapacityUnits: 5
       StreamSpecification:
         StreamViewType: streamview type

Authorization on api?

It seems it's not possible to define authorization (IAM or Custom) on the implicit API created as a lambda event source. And it looks like AWS::Serverless::Api doesn't support it either? Is there any plan to add this feature?

cors: true

One thing that I like about serverless.com is that CORS can be enabled for an endpoint in one short line:

cors: true

Currently, to enable CORS using x-amazon-apigateway-integration, it is necessary to:

  • add a header to each response:
responses:
        '200':
          description: Request successful
          headers:
            Access-Control-Allow-Origin:
              type: string
          schema:
            $ref: '#/definitions/Success'
        '400':
          description: Authentication failed
          headers:
            Access-Control-Allow-Origin:
              type: string
          schema:
            $ref: '#/definitions/Error'
  • add responseParameters in x-amazon-apigateway-integration:
default:
            statusCode: "200"
            responseParameters:
              method.response.header.Access-Control-Allow-Origin : "'*'"
          '.*"status":400.*':
            statusCode: '400'
            responseParameters:
              method.response.header.Access-Control-Allow-Origin : "'*'"
  • add a massive options section:
options:
      summary: CORS support
      description: |
        Enable CORS by returning correct headers
      responses:
        200:
          description: Default response for CORS method
          headers:
            Access-Control-Allow-Headers:
              type: string
            Access-Control-Allow-Methods:
              type: string
            Access-Control-Allow-Origin:
              type: string
      x-amazon-apigateway-integration:
        type: mock
        requestTemplates:
          application/json: |
            {"statusCode" : 200}
        responses:
          "default":
            statusCode: "200"
            responseParameters:
              method.response.header.Access-Control-Allow-Headers : "'Content-Type,X-Amz-Date,Authorization,X-Api-Key'"
              method.response.header.Access-Control-Allow-Methods : "'*'"
              method.response.header.Access-Control-Allow-Origin : "'*'"
            responseTemplates:
              application/json: |
                {}

...it'd be great if Transform: AWS::Serverless-2016-10-31 could transform the swagger schema, automatically adding all of this if cors: true is present in the CloudFormation object

Add support for "Body" param in AWS::Serverless::Api

If you want to leverage additional capabilities of API gateway (i.e CORS support, mock requests, etc) you'll need to create a swagger doc. The only option right now is to create a swagger file, upload it to S3, and reference it via the DefinitionUri template.

As #8 alludes to, if you want to share data, you'll have to coordinate the variables section in AWS::Serverless::Api with the ${stageVariables.<foo>} in the swagger file.

It would be really helpful to support the Body param from http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html.

Benefits:

  1. Can leverage all the cloudformation functions within the swagger body.
  2. Simplifies process for tools wanting to generate SAM templates. Everything (except the lambda deployment package) can be in a single file vs. generating a swagger file, uploading to s3, generating a SAM template that references the swagger file.

Not possible to have CodeUri as a parameter

For some reason, it doesn't seem possible to specify CodeUri as a parameter.

I have a template that specifies a function:

AWSTemplateFormatVersion : '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: A hello world application.
Parameters:
  CodeUri:
    Type: String
    Description: The link to the code to use.
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.handler
      Runtime: nodejs4.3
      CodeUri: !Ref CodeUri

When I try to execute the template using aws cloudformation deploy the following error appears:

aws cloudformation deploy --stack-name example --template-file lambda-example.sam.yaml --parameter-overrides CodeUri=s3://$BUCKET_NAME/example.zip

Failed to create the changeset: Waiter ChangeSetCreateComplete failed: Waiter encountered a terminal failure state Status: FAILED. Reason: Transform AWS::Serverless-2016-10-31 failed with: Invalid Serverless Application Specification document. Number of errors found: 1. Resource with id [HelloWorldFunction] is invalid. 'CodeUri' is not a valid S3 Uri of the form "s3://bucket/key" with optional versionId query parameter.

I tried running it with the --debug flag attached and it looks like the correct S3 Uri is added. Below is an extract from the debug output:

    <Parameters>
      <member>
        <ParameterKey>CodeUri</ParameterKey>
        <ParameterValue>s3://johannes-lambda-test/example.zip</ParameterValue>
      </member>
    </Parameters>

The example code that have been used can be found at https://github.com/Pelto/aws-serverless-2016-10-31-bug

Code pipline fails: ChangeSetNotFound; Request ID: d0519f50-c952-11e6-90c7-533dc3f576eb)

Hi,
My serverless pipline fails due to the following error in the execution phase.
Error:

Action execution failed
ChangeSet [ProdChangeSet] does not exist (Service: AmazonCloudFormation; Status Code: 404; Error Code: ChangeSetNotFound; Request ID: d0519f50-c952-11e6-90c7-533dc3f576eb)

Looks like I need to create a changeset in cloudformation service but in the cloud formation under changeset I see the following message

There are no executable change sets. Your stack must be in an updatable state to use change sets.

api_swagger_cors example fails with api event reference error

Steps to reproduce:

  • cd serverless-application-model/examples/2016-10-31/api_swagger_cors
  • aws cloudformation package --template-file template.yaml --output-template-file packaged_template.yaml --s3-bucket <bucketname>
  • aws cloudformation deploy --template-file packaged_template.yaml --stack-name MySamSwagger --capabilities CAPABILITY_IAM

The deploy step above produces the following output error:

Waiting for changeset to be created..

Failed to create the changeset: Waiter ChangeSetCreateComplete failed: Waiter encountered a terminal failure state Status: FAILED. Reason: Transform AWS::Serverless-2016-10-31 failed with: Invalid Serverless Application Specification document. Number of errors found: 1. Resource with id [LambdaFunction] is invalid. Event with id [ProxyApiRoot] is invalid. RestApiId property of Api event must reference a valid resource in the same template.

I'm very confident that this bug was introduced after 2016-12-21T23:00:00Z, because I had a successful deployment around that time.

Typo in Attribute value for Serverless::Function

Hi,

There is currently a typo in the attribute value returned out of a Serverless:Function resource - It should be Arn instead of FunctionArn.

This works

Outputs:
    MyFunction:
      Description: "My Function ARN"
      Value: !GetAtt MyFunctionResource.Arn

This doesn't work

Outputs:
    MyFunction:
      Description: "My Function ARN"
      Value: !GetAtt MyFunctionResource.FunctionArn

AWS::ApiGateway::UsagePlan cannot use a stage from AWS::Serverless::Api

I have a AWS::Serverless::Api defined as

     Type: AWS::Serverless::Api
     Properties:
        StageName: test
        DefinitionUri: swagger.json

and a AWS::ApiGateway::UsagePlan defined as

    Type: AWS::ApiGateway::UsagePlan
    Properties:
      ApiStages:
        -
          ApiId: !Ref MyApiResource
          Stage: test
      Throttle:
        BurstLimit: 500
        RateLimit: 50
      UsagePlanName:
        Fn::Join: [
            "_",
            [
              "UsagePlan",
              !Ref "AWS::Region",
              !Ref "AWS::StackName"
            ]
          ]

If I run the cloud formation script it fails to create the UsagePlan with an error saying the stage test does not exist on the API.

If I instead comment out the usage plan and run the script and then run it again with the API and the usage plan enabled it will create the usage plan and link it to the stage properly.

Stream BatchSize property ignored in SAM template

Hi,
it seems that BatchSize specified in SAM template for DynamoDB streams is ignored.

LambdaFunction:
      ......
      Events:
        DynamoDBNewItemEvent:
          Type: DynamoDB
          Properties:
            Stream:
              "Fn::GetAtt": [ "TableFileImport", "StreamArn" ]
            StartingPosition: "LATEST"
            BatchSize: 10

I have compared the original template with processed one in CloudFormation and there is no BatchSize properties in the latter.
The stream gets default BatchSize=100

The similar issue was posted on AWS Forum but for Kinesis Streams See there

Add Support for AuthorizationType to API

API Endpoints often require authorization permissions, e.g. only IAM users. Ideally, AWS::Serverless::Api would also support AuthorizationType available for API Gateway.

For example, using IAM user:

Events:
  Type: Api
  Properties:
    Path: /secrets
    Method: get
    AuthorizationType: AWS_IAM

Or a custom authorizer:

Events:
  Type: Api
  Properties:
    Path: /secrets
    Method: get
    AuthorizationType: CUSTOM
    Authorizer: <ARN_CUSTOM_AUTHORIZER>

Realize this may be challenging in referencing the custom authorizer function if not a function defined within the template though.

Docs for Api DefinitionUri do not match examples

The docs say that the fields should be

Required S3 URI to the Swagger document describing the API.

Yet the example is of a local file:

DefinitionUri: swagger.yml

Can it be made clear whether the S3 format is enforced or if local files are also accepted, or an example of both provided if both are valid

Permissions to be set-up for S3

I want to take care of upload myself, because I do not like very much the hashes namings schema that are auto-generated. I did my own uploader but now, when I try to deploy my cloudformation, I see this in my console:

Could not unzip uploaded file. Please check your file, then try to upload again.
  • But the zip is there, what must be done ?
  • Another thing that I cannot find out is that I name my packages like this A.B.C.D.zip , is this confusing the unzip program ? Should I have ABCD.zip instead ?

Enable CORS for generated api

When using Events on a function to generate api, is it possible to enable CORS or do I have to use swagger and specify it all on my own then?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.