[AWS SAM] Introduction to Python version

Contents

It seems that sam has been updated to make it easier to use, so I will keep a memorandum of the flow from environment construction to deployment with Pipenv.

environment

table of contents

  1. Build an environment with Pipenv
  2. Application initialization
  3. Deploy

1. Build an environment with Pipenv

Pipenv installation

$ pip install pipenv

Pipenv initialization

$ pipenv --python 3.7

Enter the virtual environment

$ pipenv shell

aws-sam-cli installation

Libraries required during development can be separated by adding the --dev option.

$ pipenv install aws-sam-cli --dev

2. Application initialization

For the rest of this work, make Project name [sam-app]: the same name as the directory where pipfile etc. is located.

Template application generation

$ sam init
Which template source would you like to use?
        1 - AWS Quick Start Templates
        2 - Custom Template Location
Choice: 1

Which runtime would you like to use?
        1 - nodejs12.x
        2 - python3.8
        3 - ruby2.5
        4 - go1.x
        5 - java11
        6 - dotnetcore2.1
        7 - nodejs10.x
        8 - nodejs8.10
        9 - python3.7
        10 - python3.6
        11 - python2.7
        12 - java8
        13 - dotnetcore2.0
        14 - dotnetcore1.0
Runtime: 9

Project name [sam-app]:   aws-sam-1       

Allow SAM CLI to download AWS-provided quick start templates from Github [Y/n]: y

AWS quick start application templates:
        1 - Hello World Example
        2 - EventBridge Hello World
        3 - EventBridge App from scratch (100+ Event Schemas)
Template selection: 1

-----------------------
Generating application:
-----------------------
Name: sam-app
Runtime: python3.7
Dependency Manager: pip
Application Template: hello-world
Output Directory: .

Next steps can be found in the README file at ./aws-sam-1/README.md

With the work so far, the directory structure is like this.

.
├── Pipfile
├── Pipfile.lock
├── README.md
└── aws-sam-1
    ├── README.md
    ├── events
    │   └── event.json
    ├── hello_world
    │   ├── __init__.py
    │   ├── app.py
    │   └── requirements.txt
    ├── template.yaml
    └── tests
        └── unit
            ├── __init__.py
            └── test_handler.py

However, since it is better to be flat, bring ʻaws-sam-1 / `below to the next higher level.

$ mv ./aws-sam-1/* ./
$ rm -r ./aws-sam-1

The directory hierarchy after execution looks like this. I don't often manage multiple templates in one repository, so I like this one because it's cleaner.

.
├── Pipfile
├── Pipfile.lock
├── README.md
├── events
│   └── event.json
├── hello_world
│   ├── __init__.py
│   ├── app.py
│   └── requirements.txt
├── template.yaml
└── tests
    └── unit
        ├── __init__.py
        └── test_handler.py

Build application

$ sam build
Building resource 'HelloWorldFunction'
Running PythonPipBuilder:ResolveDependencies
Running PythonPipBuilder:CopySource

Build Succeeded

Built Artifacts  : .aws-sam/build
Built Template   : .aws-sam/build/template.yaml

Commands you can use next
=========================
[*] Invoke Function: sam local invoke
[*] Deploy: sam deploy --guided

When you run it, you can do various things under .aws-sam /. I will not explain in detail, but it is the execution script, template.yaml, library, etc. that are actually deployed.

3. Deploy

Well, it's finally deploying, but I think the update made it the easiest.

Previously, it was rather troublesome to update the source code and dependent files with sam package every time, and to specify the stack name at the time of deployment. After the update, you can add the --guided option to put them together in a file called samconfig.toml. This will allow the second and subsequent deployments to be OK with just the sam deploy command.

Now let's deploy after the update. If you have separate settings for ~ / .aws / credentials, please add the --profile option.

Deploy

$ sam deploy --guided
Configuring SAM deploy
======================

        Looking for samconfig.toml :  Not found

        Setting default arguments for 'sam deploy'
        =========================================
        Stack Name [sam-app]: aws-sam-1-stack  
        AWS Region [us-east-1]: ap-northeast-1              
        #Shows you resources changes to be deployed and require a 'Y' to initiate deploy
        Confirm changes before deploy [y/N]: y
        #SAM needs permission to be able to create roles to connect to the resources in your template
        Allow SAM CLI IAM role creation [Y/n]: 
        Save arguments to samconfig.toml [Y/n]: 

        Looking for resources needed for deployment: Not found.
        Creating the required resources...
        Successfully created!

                Managed S3 bucket: aws-sam-cli-managed-default-samclisourcebucket-1np75dr62k62n
                A different default S3 bucket can be set in samconfig.toml

        Saved arguments to config file
        Running 'sam deploy' for future deployments will use the parameters saved above.
        The above parameters can be changed by modifying samconfig.toml
        Learn more about samconfig.toml syntax at 
        https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-config.html

        Deploying with following values
        ===============================
        Stack name                 : aws-sam-1-stack
        Region                     : ap-northeast-1
        Confirm changeset          : True
        Deployment s3 bucket       : aws-sam-cli-managed-default-samclisourcebucket-1np75dr62k62n
        Capabilities               : ["CAPABILITY_IAM"]
        Parameter overrides        : {}

Initiating deployment
=====================
Uploading to aws-sam-1-stack/7f10f61137bc6dbef4059bf50229b958  532293 / 532293.0  (100.00%)
Uploading to aws-sam-1-stack/0797e53a6d5052f23f1972e20e6fd8dd.template  1102 / 1102.0  (100.00%)

Waiting for changeset to be created..

CloudFormation stack changeset
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Operation                                                           LogicalResourceId                                                   ResourceType                                                      
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
+ Add                                                               HelloWorldFunctionHelloWorldPermissionProd                          AWS::Lambda::Permission                                           
+ Add                                                               HelloWorldFunctionRole                                              AWS::IAM::Role                                                    
+ Add                                                               HelloWorldFunction                                                  AWS::Lambda::Function                                             
+ Add                                                               ServerlessRestApiDeployment47fc2d5f9d                               AWS::ApiGateway::Deployment                                       
+ Add                                                               ServerlessRestApiProdStage                                          AWS::ApiGateway::Stage                                            
+ Add                                                               ServerlessRestApi                                                   AWS::ApiGateway::RestApi                                          
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Changeset created successfully. arn:aws:cloudformation:ap-northeast-1:xxxxxxxxxxxx:changeSet/samcli-deploy1576913429/1265b6b9-05ac-4a26-9f75-d81099274672


Previewing CloudFormation changeset before deployment
======================================================
Deploy this changeset? [y/N]: y

2019-12-21 16:30:55 - Waiting for stack create/update to complete

CloudFormation events from changeset
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ResourceStatus                                     ResourceType                                       LogicalResourceId                                  ResourceStatusReason                             
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE_IN_PROGRESS                                 AWS::IAM::Role                                     HelloWorldFunctionRole                             Resource creation Initiated                      
CREATE_IN_PROGRESS                                 AWS::IAM::Role                                     HelloWorldFunctionRole                             -                                                
CREATE_COMPLETE                                    AWS::IAM::Role                                     HelloWorldFunctionRole                             -                                                
CREATE_IN_PROGRESS                                 AWS::Lambda::Function                              HelloWorldFunction                                 -                                                
CREATE_IN_PROGRESS                                 AWS::Lambda::Function                              HelloWorldFunction                                 Resource creation Initiated                      
CREATE_COMPLETE                                    AWS::Lambda::Function                              HelloWorldFunction                                 -                                                
CREATE_IN_PROGRESS                                 AWS::ApiGateway::RestApi                           ServerlessRestApi                                  -                                                
CREATE_IN_PROGRESS                                 AWS::ApiGateway::RestApi                           ServerlessRestApi                                  Resource creation Initiated                      
CREATE_COMPLETE                                    AWS::ApiGateway::RestApi                           ServerlessRestApi                                  -                                                
CREATE_IN_PROGRESS                                 AWS::Lambda::Permission                            HelloWorldFunctionHelloWorldPermissionProd         -                                                
CREATE_IN_PROGRESS                                 AWS::Lambda::Permission                            HelloWorldFunctionHelloWorldPermissionProd         Resource creation Initiated                      
CREATE_IN_PROGRESS                                 AWS::ApiGateway::Deployment                        ServerlessRestApiDeployment47fc2d5f9d              -                                                
CREATE_COMPLETE                                    AWS::ApiGateway::Deployment                        ServerlessRestApiDeployment47fc2d5f9d              -                                                
CREATE_IN_PROGRESS                                 AWS::ApiGateway::Deployment                        ServerlessRestApiDeployment47fc2d5f9d              Resource creation Initiated                      
CREATE_IN_PROGRESS                                 AWS::ApiGateway::Stage                             ServerlessRestApiProdStage                         -                                                
CREATE_IN_PROGRESS                                 AWS::ApiGateway::Stage                             ServerlessRestApiProdStage                         Resource creation Initiated                      
CREATE_COMPLETE                                    AWS::ApiGateway::Stage                             ServerlessRestApiProdStage                         -                                                
CREATE_COMPLETE                                    AWS::Lambda::Permission                            HelloWorldFunctionHelloWorldPermissionProd         -                                                
CREATE_COMPLETE                                    AWS::CloudFormation::Stack                         aws-sam-1-stack                                    -                                                
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Stack aws-sam-1-stack outputs:
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
OutputKey-Description                                                                                 OutputValue                                                                                         
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
HelloWorldFunctionIamRole - Implicit IAM Role created for Hello World function                        arn:aws:iam::xxxxxxxxxxxx:role/aws-sam-1-stack-HelloWorldFunctionRole-PB5A5G9O9MBP                  
HelloWorldApi - API Gateway endpoint URL for Prod stage for Hello World function                      https://xxxxxxxxxx.execute-api.ap-northeast-1.amazonaws.com/Prod/hello/                             
HelloWorldFunction - Hello World Lambda Function ARN                                                  arn:aws:lambda:ap-northeast-1:xxxxxxxxxxxx:function:aws-sam-1-stack-                                
                                                                                                      HelloWorldFunction-1QOQ29MG7346Z                                                                    
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Successfully created/updated stack - aws-sam-1-stack in ap-northeast-1

The deployment is now complete.

HelloWorldApi - API Gateway endpoint URL for Prod stage for Hello World function https://xxxxxxxxxx.execute-api.ap-northeast-1.amazonaws.com/Prod/hello/

The access point to API Gateway is displayed in the log, so let's access it.

curl https://xxxxxxxxxx.execute-api.ap-northeast-1.amazonaws.com/Prod/hello/
{"message": "hello world"}

If it returns, it is a success.

At the end

This time I used the tutorial app as it is, Next time, I would like to create an API by combining DynamoDB.

Repository: https://gitlab.com/tarte9572/aws-sam-1

Recommended Posts

[AWS SAM] Introduction to Python version
Introduction to Python (Python version APG4b)
Introduction to OpenCV (python)-(2)
[2020 version] How to install Python3 on AWS EC2
Introduction to Python Django (2) Win
Introduction to serial communication [Python]
How to change Python version
An introduction to Python Programming
[Introduction to Udemy Python 3 + Application] 58. Lambda
[Introduction to Udemy Python 3 + Application] 31. Comments
Introduction to Python Numerical Library NumPy
Practice! !! Introduction to Python (Type Hints)
[Introduction to Python3 Day 1] Programming and Python
[Introduction to Python] <numpy ndarray> [edit: 2020/02/22]
[Introduction to Udemy Python 3 + Application] 57. Decorator
Introduction to Python Hands On Part 1
[Introduction to Python3 Day 13] Chapter 7 Strings (7.1-7.1.1.1)
[AWS] Try adding Python library to Layer with SAM + Lambda (Python)
[Introduction to Python] How to parse JSON
[Introduction to Udemy Python 3 + Application] 56. Closure
[Introduction to Python3 Day 14] Chapter 7 Strings (7.1.1.1 to 7.1.1.4)
How to get the Python version
Introduction to Protobuf-c (C language ⇔ Python)
[Introduction to Udemy Python3 + Application] 59. Generator
[Introduction to Python3 Day 15] Chapter 7 Strings (7.1.2-7.1.2.2)
[Introduction to Python] Let's use pandas
[Introduction to Python] Let's use pandas
[Introduction to Udemy Python 3 + Application] Summary
Introduction to image analysis opencv python
[Introduction to Python] Let's use pandas
An introduction to Python for non-engineers
Python version to get unused ports
Introduction to Python Django (2) Mac Edition
[Introduction to Python3 Day 21] Chapter 10 System (10.1 to 10.5)
[Python Tutorial] An Easy Introduction to Python
[Introduction to Udemy Python3 + Application] 18. List methods
[Introduction to Udemy Python3 + Application] 63. Generator comprehension
[Introduction to Python] How to use class in Python?
[Introduction to Udemy Python3 + Application] 25. Dictionary-type method
[Introduction to Udemy Python3 + Application] 33. if statement
Introduction to Discrete Event Simulation Using Python # 1
[Introduction to Udemy Python3 + Application] 13. Character method
[Introduction to Python3, Day 17] Chapter 8 Data Destinations (8.1-8.2.5)
[Introduction to Udemy Python3 + Application] 55. In-function functions
[Introduction to Udemy Python3 + Application] 48. Function definition
[Introduction to Python3, Day 17] Chapter 8 Data Destinations (8.3-8.3.6.1)
A super introduction to Python bit operations
[Introduction to Udemy Python 3 + Application] 10. Numerical values
Introduction to Python Image Inflating Image inflating with ImageDataGenerator
Web-WF Python Tornado Part 3 (Introduction to Openpyexcel)
[Introduction to Udemy Python3 + Application] 41. Input function
[Introduction to Python] Let's use foreach with Python
[Introduction to Python3 Day 19] Chapter 8 Data Destinations (8.4-8.5)
[Introduction to Udemy Python3 + Application] 17. List operation
[Python] Introduction to CNN with Pytorch MNIST
[Introduction to Python3 Day 18] Chapter 8 Data Destinations (8.3.6.2 to 8.3.6.3)
I want to play with aws with python
How to check opencv version in python
[Introduction to Udemy Python3 + Application] 11. Character strings
[Introduction to Udemy Python3 + Application] 44. range function
[Introduction to Udemy Python3 + Application] 46. Zip function