# HG changeset patch # User Dennis Concepcion Martin # Date 1631777887 -7200 # Node ID 0277e7fc0f0a8e8068150eb58a3f4d3720dbb3ad # Parent cea9500dca25d38a03c024c3d62a81884d2b7646 first successful sam deploy diff -r cea9500dca25 -r 0277e7fc0f0a .aws-sam/build.toml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/.aws-sam/build.toml Thu Sep 16 09:38:07 2021 +0200 @@ -0,0 +1,11 @@ +# This file is auto generated by SAM CLI build command + +[function_build_definitions] +[function_build_definitions.d30384fa-aa96-4ffd-9beb-35e450903b28] +codeuri = "/Users/dennis/Developer/tweet-analysis/src" +runtime = "python3.9" +source_md5 = "" +packagetype = "Zip" +functions = ["GetTweetSentimentFunction"] + +[layer_build_definitions] diff -r cea9500dca25 -r 0277e7fc0f0a .idea/vcs.xml --- a/.idea/vcs.xml Tue Sep 14 17:46:04 2021 +0200 +++ b/.idea/vcs.xml Thu Sep 16 09:38:07 2021 +0200 @@ -7,4 +7,7 @@ + + + \ No newline at end of file diff -r cea9500dca25 -r 0277e7fc0f0a README.md --- a/README.md Tue Sep 14 17:46:04 2021 +0200 +++ b/README.md Thu Sep 16 09:38:07 2021 +0200 @@ -1,36 +1,26 @@ # tweet-analysis -This project contains source code and supporting files for a serverless application that you can deploy with the SAM CLI. It includes the following files and folders. +## Structure -- hello_world - Code for the application's Lambda function. +- src - Code for the application's Lambda function. - events - Invocation events that you can use to invoke the function. - tests - Unit tests for the application code. - template.yaml - A template that defines the application's AWS resources. -The application uses several AWS resources, including Lambda functions and an API Gateway API. These resources are defined in the `template.yaml` file in this project. You can update the template to add AWS resources through the same deployment process that updates your application code. - -If you prefer to use an integrated development environment (IDE) to build and test your application, you can use the AWS Toolkit. -The AWS Toolkit is an open source plug-in for popular IDEs that uses the SAM CLI to build and deploy serverless applications on AWS. The AWS Toolkit also adds a simplified step-through debugging experience for Lambda function code. See the following links to get started. +The application uses several AWS resources, including Lambda functions and an API Gateway API. +These resources are defined in the `template.yaml` file in this project. You can update the template to add AWS +resources through the same deployment process that updates your application code. -* [CLion](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) -* [GoLand](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) -* [IntelliJ](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) -* [WebStorm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) -* [Rider](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) -* [PhpStorm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) -* [PyCharm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) -* [RubyMine](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) -* [DataGrip](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) -* [VS Code](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/welcome.html) -* [Visual Studio](https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/welcome.html) +## Deploy the application -## Deploy the sample application - -The Serverless Application Model Command Line Interface (SAM CLI) is an extension of the AWS CLI that adds functionality for building and testing Lambda applications. It uses Docker to run your functions in an Amazon Linux environment that matches Lambda. It can also emulate your application's build environment and API. +The Serverless Application Model Command Line Interface (SAM CLI) is an extension of the AWS CLI that adds functionality +for building and testing Lambda applications. It uses Docker to run your functions in an Amazon Linux environment that +matches Lambda. It can also emulate your application's build environment and API. To use the SAM CLI, you need the following tools. -* SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) +* SAM CLI - +[Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) * [Python 3 installed](https://www.python.org/downloads/) * Docker - [Install Docker community edition](https://hub.docker.com/search/?type=edition&offering=community) @@ -41,16 +31,27 @@ sam deploy --guided ``` -The first command will build the source of your application. The second command will package and deploy your application to AWS, with a series of prompts: +The first command will build the source of your application. The second command will package and deploy your application +to AWS, with a series of prompts: -* **Stack Name**: The name of the stack to deploy to CloudFormation. This should be unique to your account and region, and a good starting point would be something matching your project name. +* **Stack Name**: The name of the stack to deploy to CloudFormation. This should be unique to your account and region, +and a good starting point would be something matching your project name. * **AWS Region**: The AWS region you want to deploy your app to. -* **Confirm changes before deploy**: If set to yes, any change sets will be shown to you before execution for manual review. If set to no, the AWS SAM CLI will automatically deploy application changes. -* **Allow SAM CLI IAM role creation**: Many AWS SAM templates, including this example, create AWS IAM roles required for the AWS Lambda function(s) included to access AWS services. By default, these are scoped down to minimum required permissions. To deploy an AWS CloudFormation stack which creates or modifies IAM roles, the `CAPABILITY_IAM` value for `capabilities` must be provided. If permission isn't provided through this prompt, to deploy this example you must explicitly pass `--capabilities CAPABILITY_IAM` to the `sam deploy` command. -* **Save arguments to samconfig.toml**: If set to yes, your choices will be saved to a configuration file inside the project, so that in the future you can just re-run `sam deploy` without parameters to deploy changes to your application. +* **Confirm changes before deploy**: If set to yes, any change sets will be shown to you before execution for manual +review. If set to no, the AWS SAM CLI will automatically deploy application changes. +* **Allow SAM CLI IAM role creation**: Many AWS SAM templates, including this example, create AWS IAM roles required +for the AWS Lambda function(s) included to access AWS services. By default, these are scoped down to minimum required +permissions. To deploy an AWS CloudFormation stack which creates or modifies IAM roles, the `CAPABILITY_IAM` value for +`capabilities` must be provided. If permission isn't provided through this prompt, to deploy this example you must +explicitly pass `--capabilities CAPABILITY_IAM` to the `sam deploy` command. +* **Save arguments to `samconfig.toml`**: If set to yes, your choices will be saved to a configuration file inside the +project, so that in the future you can just re-run `sam deploy` without parameters to deploy changes to your application. You can find your API Gateway Endpoint URL in the output values displayed after deployment. +**If a certificate in AWS Certificate Manager is created with the template, you have to create manually the DNS +validation record to issue the certificate** + ## Use the SAM CLI to build and test locally Build your application with the `sam build --use-container` command. @@ -59,9 +60,11 @@ tweet-analysis$ sam build --use-container ``` -The SAM CLI installs dependencies defined in `hello_world/requirements.txt`, creates a deployment package, and saves it in the `.aws-sam/build` folder. +The SAM CLI installs dependencies defined in `src/requirements.txt`, creates a deployment package, and saves it in the +`.aws-sam/build` folder. -Test a single function by invoking it directly with a test event. An event is a JSON document that represents the input that the function receives from the event source. Test events are included in the `events` folder in this project. +Test a single function by invoking it directly with a test event. An event is a JSON document that represents the input +that the function receives from the event source. Test events are included in the `events` folder in this project. Run functions locally and invoke them with the `sam local invoke` command. @@ -76,7 +79,8 @@ tweet-analysis$ curl http://localhost:3000/ ``` -The SAM CLI reads the application template to determine the API's routes and the functions that they invoke. The `Events` property on each function's definition includes the route and method for each path. +The SAM CLI reads the application template to determine the API's routes and the functions that they invoke. The +`Events` property on each function's definition includes the route and method for each path. ```yaml Events: @@ -88,11 +92,19 @@ ``` ## Add a resource to your application -The application template uses AWS Serverless Application Model (AWS SAM) to define application resources. AWS SAM is an extension of AWS CloudFormation with a simpler syntax for configuring common serverless application resources such as functions, triggers, and APIs. For resources not included in [the SAM specification](https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md), you can use standard [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html) resource types. +The application template uses AWS Serverless Application Model (AWS SAM) to define application resources. AWS SAM is an +extension of AWS CloudFormation with a simpler syntax for configuring common serverless application resources such as +functions, triggers, and APIs. For resources not included in +[the SAM specification](https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md), +you can use standard +[AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html) +resource types. ## Fetch, tail, and filter Lambda function logs -To simplify troubleshooting, SAM CLI has a command called `sam logs`. `sam logs` lets you fetch logs generated by your deployed Lambda function from the command line. In addition to printing the logs on the terminal, this command has several nifty features to help you quickly find the bug. +To simplify troubleshooting, SAM CLI has a command called `sam logs`. `sam logs` lets you fetch logs generated by your +deployed Lambda function from the command line. In addition to printing the logs on the terminal, this command has +several nifty features to help you quickly find the bug. `NOTE`: This command works for all AWS Lambda functions; not just the ones you deploy using SAM. @@ -100,7 +112,8 @@ tweet-analysis$ sam logs -n HelloWorldFunction --stack-name tweet-analysis --tail ``` -You can find more information and examples about filtering Lambda function logs in the [SAM CLI Documentation](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-logging.html). +You can find more information and examples about filtering Lambda function logs in the +[SAM CLI Documentation](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-logging.html). ## Tests @@ -117,7 +130,8 @@ ## Cleanup -To delete the sample application that you created, use the AWS CLI. Assuming you used your project name for the stack name, you can run the following: +To delete the sample application that you created, use the AWS CLI. Assuming you used your project name for the stack +name, you can run the following: ```bash aws cloudformation delete-stack --stack-name tweet-analysis @@ -125,6 +139,9 @@ ## Resources -See the [AWS SAM developer guide](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html) for an introduction to SAM specification, the SAM CLI, and serverless application concepts. +See the [AWS SAM developer guide](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html) +for an introduction to SAM specification, the SAM CLI, and serverless application concepts. -Next, you can use AWS Serverless Application Repository to deploy ready to use Apps that go beyond hello world samples and learn how authors developed their applications: [AWS Serverless Application Repository main page](https://aws.amazon.com/serverless/serverlessrepo/) +Next, you can use AWS Serverless Application Repository to deploy ready to use Apps that go beyond hello world samples +and learn how authors developed their applications: +[AWS Serverless Application Repository main page](https://aws.amazon.com/serverless/serverlessrepo/) diff -r cea9500dca25 -r 0277e7fc0f0a events/event.json --- a/events/event.json Tue Sep 14 17:46:04 2021 +0200 +++ b/events/event.json Thu Sep 16 09:38:07 2021 +0200 @@ -1,7 +1,7 @@ { "body": "{\"message\": \"hello world\"}", - "resource": "/hello", - "path": "/hello", + "resource": "/sentiment", + "path": "/sentiment", "httpMethod": "GET", "isBase64Encoded": false, "queryStringParameters": { diff -r cea9500dca25 -r 0277e7fc0f0a hello_world/__init__.py diff -r cea9500dca25 -r 0277e7fc0f0a hello_world/app.py --- a/hello_world/app.py Tue Sep 14 17:46:04 2021 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,42 +0,0 @@ -import json - -# import requests - - -def lambda_handler(event, context): - """Sample pure Lambda function - - Parameters - ---------- - event: dict, required - API Gateway Lambda Proxy Input Format - - Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format - - context: object, required - Lambda Context runtime methods and attributes - - Context doc: https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html - - Returns - ------ - API Gateway Lambda Proxy Output Format: dict - - Return doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html - """ - - # try: - # ip = requests.get("http://checkip.amazonaws.com/") - # except requests.RequestException as e: - # # Send some context about this error to Lambda Logs - # print(e) - - # raise e - - return { - "statusCode": 200, - "body": json.dumps({ - "message": "hello world", - # "location": ip.text.replace("\n", "") - }), - } diff -r cea9500dca25 -r 0277e7fc0f0a hello_world/requirements.txt --- a/hello_world/requirements.txt Tue Sep 14 17:46:04 2021 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,1 +0,0 @@ -requests \ No newline at end of file diff -r cea9500dca25 -r 0277e7fc0f0a samconfig.toml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/samconfig.toml Thu Sep 16 09:38:07 2021 +0200 @@ -0,0 +1,11 @@ +version = 0.1 +[default] +[default.deploy] +[default.deploy.parameters] +stack_name = "tweet-analysis" +s3_bucket = "aws-sam-cli-managed-default-samclisourcebucket-696e2vcoot9k" +s3_prefix = "tweet-analysis" +region = "eu-west-2" +confirm_changeset = true +capabilities = "CAPABILITY_IAM" +image_repositories = [] diff -r cea9500dca25 -r 0277e7fc0f0a src/__init__.py diff -r cea9500dca25 -r 0277e7fc0f0a src/handlers/__init__.py diff -r cea9500dca25 -r 0277e7fc0f0a src/handlers/sentiment.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/handlers/sentiment.py Thu Sep 16 09:38:07 2021 +0200 @@ -0,0 +1,22 @@ +import json + + +def get_tweet_sentiment(event, context): + """ + + :param event: dict, required + API Gateway Lambda Proxy Input Format + :param context: object, required + Lambda Context runtime methods and attributes + :return: dict + API Gateway Lambda Proxy Output Format + """ + + print('hello world') + + return { + "statusCode": 200, + "body": json.dumps({ + "message": "hello world" + }), + } diff -r cea9500dca25 -r 0277e7fc0f0a src/requirements.txt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/requirements.txt Thu Sep 16 09:38:07 2021 +0200 @@ -0,0 +1,1 @@ +requests \ No newline at end of file diff -r cea9500dca25 -r 0277e7fc0f0a template.yaml --- a/template.yaml Tue Sep 14 17:46:04 2021 +0200 +++ b/template.yaml Thu Sep 16 09:38:07 2021 +0200 @@ -1,39 +1,84 @@ AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 -Description: > - tweet-analysis +Description: Fetch & analyse tweets using AWS Comprehend - Sample SAM Template for tweet-analysis - -# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst +# Global Settings Globals: Function: Timeout: 3 + Tags: + application-id: "tweet-analysis" + Api: + Auth: + ApiKeyRequired: true + UsagePlan: + CreateUsagePlan: PER_API Resources: - HelloWorldFunction: - Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction + # Create custom domain in Api Gateway + Domain: + Type: AWS::ApiGateway::DomainName Properties: - CodeUri: hello_world/ - Handler: app.lambda_handler - Runtime: python3.9 - 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 + RegionalCertificateArn: !Ref DomainCertificate + DomainName: tweet-analysis.dennistech.io + SecurityPolicy: TLS_1_2 + EndpointConfiguration: + Types: + - REGIONAL + Tags: + - Key: "application-id" + Value: "tweet-analysis" + - Key: "Name" + Value: "tweet-analysis::api-custom-domain" + + # Create domain SSL certificate + DomainCertificate: + Type: AWS::CertificateManager::Certificate + Properties: + DomainName: tweet-analysis.dennistech.io + ValidationMethod: DNS + DomainValidationOptions: + - DomainName: tweet-analysis.dennistech.io + HostedZoneId: Z0937998E3C5GEK4NHO9 + Tags: + - Key: "application-id" + Value: "tweet-analysis" + - Key: "Name" + Value: "tweet-analysis::certificate::dennistech.io" -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/" - HelloWorldFunction: - Description: "Hello World Lambda Function ARN" - Value: !GetAtt HelloWorldFunction.Arn - HelloWorldFunctionIamRole: - Description: "Implicit IAM Role created for Hello World function" - Value: !GetAtt HelloWorldFunctionRole.Arn + # Map domain to the regional domain generated by Api Gateway + DomainMapping: + Type: AWS::Route53::RecordSet + Properties: + HostedZoneId: Z0937998E3C5GEK4NHO9 + Name: tweet-analysis.dennistech.io + Type: A + AliasTarget: + DNSName: !GetAtt Domain.RegionalDomainName + EvaluateTargetHealth: true + HostedZoneId: !GetAtt Domain.RegionalHostedZoneId + + # Map paths from your domain name to your API stages + PathMapping: + Type: AWS::ApiGateway::BasePathMapping + Properties: + DomainName: !Ref Domain + RestApiId: !Ref ServerlessRestApi + Stage: Prod + + # Define lambda functions + GetTweetSentimentFunction: + Type: AWS::Serverless::Function + Properties: + Description: Fetch tweets and analyse sentiment using AWS Comprehend + CodeUri: src/ + Handler: handlers/sentiment.get_tweet_sentiment + Runtime: python3.9 + Tags: + Name: "tweet-analysis::get-tweet-sentiment-function" + Events: + CallGetTweetSentiment: + Type: Api + Properties: + Path: /sentiment + Method: get diff -r cea9500dca25 -r 0277e7fc0f0a tests/integration/test_api_gateway.py --- a/tests/integration/test_api_gateway.py Tue Sep 14 17:46:04 2021 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,55 +0,0 @@ -import os -from unittest import TestCase - -import boto3 -import requests - -""" -Make sure env variable AWS_SAM_STACK_NAME exists with the name of the stack we are going to test. -""" - - -class TestApiGateway(TestCase): - api_endpoint: str - - @classmethod - def get_stack_name(cls) -> str: - stack_name = os.environ.get("AWS_SAM_STACK_NAME") - if not stack_name: - raise Exception( - "Cannot find env var AWS_SAM_STACK_NAME. \n" - "Please setup this environment variable with the stack name where we are running integration tests." - ) - - return stack_name - - def setUp(self) -> None: - """ - Based on the provided env variable AWS_SAM_STACK_NAME, - here we use cloudformation API to find out what the HelloWorldApi URL is - """ - stack_name = TestApiGateway.get_stack_name() - - client = boto3.client("cloudformation") - - try: - response = client.describe_stacks(StackName=stack_name) - except Exception as e: - raise Exception( - f"Cannot find stack {stack_name}. \n" f'Please make sure stack with the name "{stack_name}" exists.' - ) from e - - stacks = response["Stacks"] - - stack_outputs = stacks[0]["Outputs"] - api_outputs = [output for output in stack_outputs if output["OutputKey"] == "HelloWorldApi"] - self.assertTrue(api_outputs, f"Cannot find output HelloWorldApi in stack {stack_name}") - - self.api_endpoint = api_outputs[0]["OutputValue"] - - def test_api_gateway(self): - """ - Call the API Gateway endpoint and check the response - """ - response = requests.get(self.api_endpoint) - self.assertDictEqual(response.json(), {"message": "hello world"}) diff -r cea9500dca25 -r 0277e7fc0f0a tests/unit/test_handler.py --- a/tests/unit/test_handler.py Tue Sep 14 17:46:04 2021 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,73 +0,0 @@ -import json - -import pytest - -from hello_world import app - - -@pytest.fixture() -def apigw_event(): - """ Generates API GW Event""" - - return { - "body": '{ "test": "body"}', - "resource": "/{proxy+}", - "requestContext": { - "resourceId": "123456", - "apiId": "1234567890", - "resourcePath": "/{proxy+}", - "httpMethod": "POST", - "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", - "accountId": "123456789012", - "identity": { - "apiKey": "", - "userArn": "", - "cognitoAuthenticationType": "", - "caller": "", - "userAgent": "Custom User Agent String", - "user": "", - "cognitoIdentityPoolId": "", - "cognitoIdentityId": "", - "cognitoAuthenticationProvider": "", - "sourceIp": "127.0.0.1", - "accountId": "", - }, - "stage": "prod", - }, - "queryStringParameters": {"foo": "bar"}, - "headers": { - "Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)", - "Accept-Language": "en-US,en;q=0.8", - "CloudFront-Is-Desktop-Viewer": "true", - "CloudFront-Is-SmartTV-Viewer": "false", - "CloudFront-Is-Mobile-Viewer": "false", - "X-Forwarded-For": "127.0.0.1, 127.0.0.2", - "CloudFront-Viewer-Country": "US", - "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", - "Upgrade-Insecure-Requests": "1", - "X-Forwarded-Port": "443", - "Host": "1234567890.execute-api.us-east-1.amazonaws.com", - "X-Forwarded-Proto": "https", - "X-Amz-Cf-Id": "aaaaaaaaaae3VYQb9jd-nvCd-de396Uhbp027Y2JvkCPNLmGJHqlaA==", - "CloudFront-Is-Tablet-Viewer": "false", - "Cache-Control": "max-age=0", - "User-Agent": "Custom User Agent String", - "CloudFront-Forwarded-Proto": "https", - "Accept-Encoding": "gzip, deflate, sdch", - }, - "pathParameters": {"proxy": "/examplepath"}, - "httpMethod": "POST", - "stageVariables": {"baz": "qux"}, - "path": "/examplepath", - } - - -def test_lambda_handler(apigw_event, mocker): - - ret = app.lambda_handler(apigw_event, "") - data = json.loads(ret["body"]) - - assert ret["statusCode"] == 200 - assert "message" in ret["body"] - assert data["message"] == "hello world" - # assert "location" in data.dict_keys()