Skip to content

Commit

Permalink
chore: merge pull request #898 from awslabs/release/v1.11.0
Browse files Browse the repository at this point in the history
chore: merge release/v1.11.0 into master
  • Loading branch information
keetonian authored Apr 25, 2019
2 parents 62d69cb + f7969bf commit cccb0c9
Show file tree
Hide file tree
Showing 116 changed files with 8,493 additions and 289 deletions.
32 changes: 30 additions & 2 deletions HOWTO.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,15 @@ resources for you.
The remainder of this document explains how to write SAM templates and
deploy them via AWS CloudFormation.

## Writing SAM Template
## Getting started with the SAM Template
Check out the [latest specification](versions/2016-10-31.md) for details on how to write a SAM template


You could also use the [aws-sam-cli](https://github.com/awslabs/aws-sam-cli) to get started

```shell
$ sam init --runtime python3.7
```
## Packing Artifacts
Before you can deploy a SAM template, you should first upload your Lambda
function code zip and API's OpenAPI File to S3. Set the `CodeUri` and
Expand Down Expand Up @@ -47,9 +53,22 @@ packaged template that can be readily deployed to CloudFormation.
$ aws cloudformation package \
--template-file /path_to_template/template.yaml \
--s3-bucket bucket-name \
--s3-prefix appname/branchname/version
--output-template-file packaged-template.yaml
```

Or using the aws-sam-cli

```bash
$ sam package \
--template-file /path_to_template/template.yaml \
--s3-bucket bucket-name \
--s3-prefix appname/branchname/version
--output-template-file packaged-template.yaml
```



The packaged template will look something like this:
```YAML
MyLambdaFunction:
Expand Down Expand Up @@ -80,7 +99,16 @@ $ aws cloudformation deploy \
--capabilities CAPABILITY_IAM
```

Refer to the [documentation](http://docs.aws.amazon.com/cli/latest/reference/cloudformation/deploy/index.html) for more details.
Or using aws-sam-cli

```bash
$ sam deploy \
--template-file /path_to_template/packaged-template.yaml \
--stack-name my-new-stack
--capabilities CAPABILITY_IAM
```

Refer to the [cloudformation documentation](http://docs.aws.amazon.com/cli/latest/reference/cloudformation/deploy/index.html) and [samcli](https://github.com/awslabs/aws-sam-cli) for more details.

## Using Intrinsic Functions
CloudFormation provides handy functions that you can use to generate values at runtime. These are called [Intrinsic Functions](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference.html). Since SAM is deployed using CloudFormation, you can use these intrinsic functions within SAM as well. Here are some examples:
Expand Down
98 changes: 87 additions & 11 deletions bin/sam-translate.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,42 +5,91 @@
Known limitations: cannot transform CodeUri pointing at local directory.
Usage:
sam-translate.py --input-file=sam-template.yaml [--output-file=<o>]
sam-translate.py --template-file=sam-template.yaml [--verbose] [--output-template=<o>]
sam-translate.py package --template-file=sam-template.yaml --s3-bucket=my-bucket [--verbose] [--output-template=<o>]
sam-translate.py deploy --template-file=sam-template.yaml --s3-bucket=my-bucket --capabilities=CAPABILITY_NAMED_IAM --stack-name=my-stack [--verbose] [--output-template=<o>]
Options:
--input-file=<i> Location of SAM template to transform.
--output-file=<o> Location to store resulting CloudFormation template [default: cfn-template.json].
--template-file=<i> Location of SAM template to transform [default: template.yaml].
--output-template=<o> Location to store resulting CloudFormation template [default: transformed-template.json].
--s3-bucket=<s> S3 bucket to use for SAM artifacts when using the `package` command
--capabilities=<c> Capabilities
--stack-name=<n> Unique name for your CloudFormation Stack
--verbose Enables verbose logging
"""
import json
import logging
import os
import platform
import subprocess
import sys

import boto3
from docopt import docopt

my_path = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, my_path + '/..')

from samtranslator.public.translator import ManagedPolicyLoader
from samtranslator.translator.transform import transform
from samtranslator.yaml_helper import yaml_parse
from samtranslator.model.exceptions import InvalidDocumentException


LOG = logging.getLogger(__name__)
cli_options = docopt(__doc__)
iam_client = boto3.client('iam')
cwd = os.getcwd()

if cli_options.get('--verbose'):
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig()

def execute_command(command, args):
try:
aws_cmd = 'aws' if platform.system().lower() != 'windows' else 'aws.cmd'
command_with_args = [aws_cmd, 'cloudformation', command] + list(args)

LOG.debug("Executing command: %s", command_with_args)

subprocess.check_call(command_with_args)

LOG.debug("Command successful")
except subprocess.CalledProcessError as e:
# Underlying aws command will print the exception to the user
LOG.debug("Exception: %s", e)
sys.exit(e.returncode)


def get_input_output_file_paths():
input_file_option = cli_options.get('--input-file')
output_file_option = cli_options.get('--output-file')
input_file_option = cli_options.get('--template-file')
output_file_option = cli_options.get('--output-template')
input_file_path = os.path.join(cwd, input_file_option)
output_file_path = os.path.join(cwd, output_file_option)

return input_file_path, output_file_path


def main():
input_file_path, output_file_path = get_input_output_file_paths()
def package(input_file_path, output_file_path):
template_file = input_file_path
package_output_template_file = input_file_path + '._sam_packaged_.yaml'
s3_bucket = cli_options.get('--s3-bucket')
args = [
'--template-file',
template_file,
'--output-template-file',
package_output_template_file,
'--s3-bucket',
s3_bucket
]

execute_command('package', args)

return package_output_template_file


def transform_template(input_file_path, output_file_path):
with open(input_file_path, 'r') as f:
sam_template = yaml_parse(f)

Expand All @@ -56,10 +105,37 @@ def main():
print('Wrote transformed CloudFormation template to: ' + output_file_path)
except InvalidDocumentException as e:
errorMessage = reduce(lambda message, error: message + ' ' + error.message, e.causes, e.message)
print(errorMessage)
LOG.error(errorMessage)
errors = map(lambda cause: cause.message, e.causes)
print(errors)
LOG.error(errors)


def deploy(template_file):
capabilities = cli_options.get('--capabilities')
stack_name = cli_options.get('--stack-name')
args = [
'--template-file',
template_file,
'--capabilities',
capabilities,
'--stack-name',
stack_name
]

execute_command('deploy', args)

return package_output_template_file


if __name__ == '__main__':
main()
input_file_path, output_file_path = get_input_output_file_paths()

if cli_options.get('package'):
package_output_template_file = package(input_file_path, output_file_path)
transform_template(package_output_template_file, output_file_path)
elif cli_options.get('deploy'):
package_output_template_file = package(input_file_path, output_file_path)
transform_template(package_output_template_file, output_file_path)
deploy(output_file_path)
else:
transform_template(input_file_path, output_file_path)
2 changes: 2 additions & 0 deletions docs/globals.rst
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ Currently, the following resources and properties are being supported:
AutoPublishAlias:
DeploymentPreference:
PermissionsBoundary:
ReservedConcurrentExecutions:
Api:
# Properties of AWS::Serverless::Api
Expand All @@ -82,6 +83,7 @@ Currently, the following resources and properties are being supported:
BinaryMediaTypes:
MinimumCompressionSize:
Cors:
GatewayResponses:
AccessLogSetting:
CanarySetting:
TracingEnabled:
Expand Down
2 changes: 1 addition & 1 deletion docs/safe_lambda_deployments.rst
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ resource:
Action:
- "codedeploy:PutLifecycleEventHookExecutionStatus"
Resource:
!Sub 'arn:aws:codedeploy:${AWS::Region}:${AWS::AccountId}:deploymentgroup:${ServerlessDeploymentApplication}/*'
!Sub 'arn:${AWS::Partition}:codedeploy:${AWS::Region}:${AWS::AccountId}:deploymentgroup:${ServerlessDeploymentApplication}/*'
- Version: "2012-10-17"
Statement:
- Effect: "Allow"
Expand Down
7 changes: 7 additions & 0 deletions examples/2016-10-31/api_aws_iam_auth/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
exports.handler = async (event) => {
return {
statusCode: 200,
body: JSON.stringify(event),
headers: {}
}
}
30 changes: 30 additions & 0 deletions examples/2016-10-31/api_aws_iam_auth/template.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: API Gateway with AWS IAM Authorizer
Resources:
MyApi:
Type: AWS::Serverless::Api
Properties:
StageName: Prod
Auth:
DefaultAuthorizer: AWS_IAM
InvokeRole: CALLER_CREDENTIALS

MyFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: .
Handler: index.handler
Runtime: nodejs8.10
Events:
GetRoot:
Type: Api
Properties:
RestApiId: !Ref MyApi
Path: /
Method: get

Outputs:
ApiURL:
Description: "API URL"
Value: !Sub 'https://${MyApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/'
2 changes: 1 addition & 1 deletion examples/2016-10-31/api_cognito_auth/template.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ Resources:
Action: lambda:InvokeFunction
FunctionName: !GetAtt PreSignupLambdaFunction.Arn
Principal: cognito-idp.amazonaws.com
SourceArn: !Sub 'arn:aws:cognito-idp:${AWS::Region}:${AWS::AccountId}:userpool/${MyCognitoUserPool}'
SourceArn: !Sub 'arn:${AWS::Partition}:cognito-idp:${AWS::Region}:${AWS::AccountId}:userpool/${MyCognitoUserPool}'
# TODO: Add a CognitoUserPool Event Source to SAM to create this permission for you.
# Events:
# CognitoUserPoolPreSignup:
Expand Down
33 changes: 33 additions & 0 deletions examples/2016-10-31/api_gateway_responses/template.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: Simple webservice deomnstrating gateway responses.

Resources:
MyApi:
Type: AWS::Serverless::Api
Properties:
StageName: Prod
GatewayResponses:
DEFAULT_4xx:
ResponseParameters:
Headers:
Access-Control-Expose-Headers: "'WWW-Authenticate'"
Access-Control-Allow-Origin: "'*'"

GetFunction:
Type: AWS::Serverless::Function
Properties:
Handler: index.get
Runtime: nodejs6.10
InlineCode: module.exports = async () => throw new Error('Check out the response headers!')
Events:
GetResource:
Type: Api
Properties:
Path: /error
Method: get
RestApiId: !Ref MyApi
Outputs:
ApiURL:
Description: "API endpoint URL for Prod environment"
Value: !Sub "https://${MyApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/error/"
2 changes: 1 addition & 1 deletion examples/2016-10-31/inline_swagger/template.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ Resources:
httpMethod: POST
type: aws_proxy
uri:
Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${MyLambdaFunction.Arn}/invocations
Fn::Sub: arn:${AWS::Partition}:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${MyLambdaFunction.Arn}/invocations
responses: {}


Expand Down
2 changes: 1 addition & 1 deletion examples/2016-10-31/lambda_safe_deployments/template.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ Resources:
Action:
- "codedeploy:PutLifecycleEventHookExecutionStatus"
Resource:
!Sub 'arn:aws:codedeploy:${AWS::Region}:${AWS::AccountId}:deploymentgroup:${ServerlessDeploymentApplication}/*'
!Sub 'arn:${AWS::Partition}:codedeploy:${AWS::Region}:${AWS::AccountId}:deploymentgroup:${ServerlessDeploymentApplication}/*'
- Version: "2012-10-17"
Statement:
- Effect: "Allow"
Expand Down
2 changes: 1 addition & 1 deletion samtranslator/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = '1.10.0'
__version__ = '1.11.0'
Loading

0 comments on commit cccb0c9

Please sign in to comment.