Page tree
Skip to end of metadata
Go to start of metadata

Quickstart

AWS Developer Guide#AWSSAM-ServerlessApplicationModel | AWS Event Driven Architecture#DI2:InvestigateDynamicwebsiteviaS3andLambda

https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html


Installing SAM

AWS SAM on OSX

https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install-mac.html



brew update
git -C /usr/local/Homebrew/Library/Taps/homebrew/homebrew-core fetch --unshallow
brew update
brew tap aws/tap
brew install aws-sam-cli
Error: python@3.8: the bottle needs the Apple Command Line Tools to be installed.
  You can install them, if desired, with:
    xcode-select --install

xcode-select --install
5 min
brew install aws-sam-cli
Error: aws-sam-cli 0.34.0 is already installed
To upgrade to 1.23.0, run: brew upgrade aws/tap/aws-sam-cli
brew upgrade aws/tap/aws-sam-cli
==> Installing aws/tap/aws-sam-cli dependency: gdbm
==> Installing aws/tap/aws-sam-cli dependency: mpdecimal
==> Installing aws/tap/aws-sam-cli dependency: openssl@1.1
==> Installing aws/tap/aws-sam-cli dependency: readline
==> Installing aws/tap/aws-sam-cli dependency: sqlite
==> Installing aws/tap/aws-sam-cli dependency: tcl-tk
==> Installing aws/tap/aws-sam-cli dependency: python@3.8
==> Installing aws/tap/aws-sam-cli
==> Pouring aws-sam-cli-1.23.0.sierra.bottle.tar.gz

A CA file has been bootstrapped using certificates from the system
keychain. To add additional certificates, place .pem files in
  /usr/local/etc/openssl@1.1/certs

and run
  /usr/local/opt/openssl@1.1/bin/c_rehash

openssl@1.1 is keg-only, which means it was not symlinked into /usr/local,
because macOS provides LibreSSL.

If you need to have openssl@1.1 first in your PATH, run:
  echo 'export PATH="/usr/local/opt/openssl@1.1/bin:$PATH"' >> /Users/mi/.bash_profile

For compilers to find openssl@1.1 you may need to set:
  export LDFLAGS="-L/usr/local/opt/openssl@1.1/lib"
  export CPPFLAGS="-I/usr/local/opt/openssl@1.1/include"

==> readline
readline is keg-only, which means it was not symlinked into /usr/local,
because macOS provides BSD libedit.

For compilers to find readline you may need to set:
  export LDFLAGS="-L/usr/local/opt/readline/lib"
  export CPPFLAGS="-I/usr/local/opt/readline/include"

==> sqlite
sqlite is keg-only, which means it was not symlinked into /usr/local,
because macOS already provides this software and installing another version in
parallel can cause all kinds of trouble.

If you need to have sqlite first in your PATH, run:
  echo 'export PATH="/usr/local/opt/sqlite/bin:$PATH"' >> /Users/mie/.bash_profile

For compilers to find sqlite you may need to set:
  export LDFLAGS="-L/usr/local/opt/sqlite/lib"
  export CPPFLAGS="-I/usr/local/opt/sqlite/include"

==> tcl-tk
tcl-tk is keg-only, which means it was not symlinked into /usr/local,
because macOS already provides this software and installing another version in
parallel can cause all kinds of trouble.

If you need to have tcl-tk first in your PATH, run:
  echo 'export PATH="/usr/local/opt/tcl-tk/bin:$PATH"' >> /Users/mn/.bash_profile

For compilers to find tcl-tk you may need to set:
  export LDFLAGS="-L/usr/local/opt/tcl-tk/lib"
  export CPPFLAGS="-I/usr/local/opt/tcl-tk/include"

==> python@3.8
Python has been installed as
  /usr/local/opt/python@3.8/bin/python3

Unversioned symlinks `python`, `python-config`, `pip` etc. pointing to
`python3`, `python3-config`, `pip3` etc., respectively, have been installed into
  /usr/local/opt/python@3.8/libexec/bin

You can install Python packages with
  /usr/local/opt/python@3.8/bin/pip3 install <package>
They will install into the site-package directory
  /usr/local/lib/python3.8/site-packages

See: https://docs.brew.sh/Homebrew-and-Python

python@3.8 is keg-only, which means it was not symlinked into /usr/local,
because this is an alternate version of another formula.

If you need to have python@3.8 first in your PATH, run:
  echo 'export PATH="/usr/local/opt/python@3.8/bin:$PATH"' >> /Users/mie/.bash_profile

For compilers to find python@3.8 you may need to set:
  export LDFLAGS="-L/usr/local/opt/python@3.8/lib"
==> python@3.9
Python has been installed as
  /usr/local/bin/python3

Unversioned symlinks `python`, `python-config`, `pip` etc. pointing to
`python3`, `python3-config`, `pip3` etc., respectively, have been installed into
  /usr/local/opt/python@3.9/libexec/bin

You can install Python packages with
  pip3 install <package>
They will install into the site-package directory
  /usr/local/lib/python3.9/site-packages

tkinter is no longer included with this formula, but it is available separately:
  brew install python-tk@3.9
See: https://docs.brew.sh/Homebrew-and-Python

sam --version
SAM CLI, version 1.23.0

follow https://aws.amazon.com/blogs/compute/uploading-to-amazon-s3-directly-from-a-web-or-mobile-application/

Lifecycle of SAM also detailed in the https://aws.amazon.com/blogs/compute/a-simpler-deployment-experience-with-aws-sam-cli/ page via the new aws-sam-cli-managed-default cloudformation stack

SAM Base Project


sam init
Which template source would you like to use?
	1 - AWS Quick Start Templates
	2 - Custom Template Location
Choice: 1
What package type would you like to use?
	1 - Zip (artifact is a zip uploaded to S3)	
	2 - Image (artifact is an image uploaded to an ECR image repository)
Package type: 1

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

Which dependency manager would you like to use?
	1 - maven
	2 - gradle
Dependency manager: 1

Project name [sam-app]: portal-sam-app

Cloning app templates from https://github.com/aws/aws-sam-cli-app-templates

AWS quick start application templates:
	1 - Hello World Example: Maven
	2 - EventBridge Hello World: Maven
	3 - EventBridge App from scratch (100+ Event Schemas): Maven
	4 - Step Functions Sample App (Stock Trader): Maven
Template selection: 1

    -----------------------
    Generating application:
    -----------------------
    Name: portal-sam-app
    Runtime: java11
    Dependency Manager: maven
    Application Template: hello-world
    Output Directory: .
    
    Next steps can be found in the README file at ./portal-sam-app/README.md

ls
HelloWorldFunction	README.md		events			template.yaml



obrienlabs:portal-sam-app mic..ien$ sam build
Building codeuri: /Users/mi..en/wse_github/portal-sam-app/HelloWorldFunction runtime: java11 metadata: {} functions: ['HelloWorldFunction']
/Users/mic../opt/mvn381/bin/mvn is using a JVM with major version 16 which is newer than 11 that is supported by AWS Lambda. The compiled function code may not run in AWS Lambda unless the project has been configured to be compatible with Java 11 using 'maven.compiler.target' in Maven.
Running JavaMavenWorkflow:CopySource
Running JavaMavenWorkflow:MavenBuild
Running JavaMavenWorkflow:MavenCopyDependency
Running JavaMavenWorkflow:MavenCopyArtifacts

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
    
obrienlabs:portal-sam-app $ sam deploy --guided

Configuring SAM deploy
======================

	Looking for config file [samconfig.toml] :  Not found

	Setting default arguments for 'sam deploy'
	=========================================
	Stack Name [sam-app]: portal-sam-app
	AWS Region [us-east-1]: us-west-2
	#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]: y
	HelloWorldFunction may not have authorization defined, Is this okay? [y/N]: y
	Save arguments to configuration file [Y/n]: y
	SAM configuration file [samconfig.toml]: 
	SAM configuration environment [default]: 

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

		Managed S3 bucket: aws-sam-cli-managed-default-samclisourcebucket-1pe99mld5v8op
		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

Uploading to portal-sam-app/53b5eb5ea38c88621614b79c5b6d9dbb  732766 / 732766  (100.00%)

	Deploying with following values
	===============================
	Stack name                   : portal-sam-app
	Region                       : us-west-2
	Confirm changeset            : True
	Deployment s3 bucket         : aws-sam-cli-managed-default-samclisourcebucket-1pe99mld5v8op
	Capabilities                 : ["CAPABILITY_IAM"]
	Parameter overrides          : {}
	Signing Profiles             : {}

Initiating deployment
=====================
Uploading to portal-sam-app/d02b438b6cadf8b46815c5a0f50c4f74.template  1204 / 1204  (100.00%)

Waiting for changeset to be created..

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

Changeset created successfully. arn:aws:cloudformation:us-west-2:45...0:changeSet/samcli-deploy1621180662/c6fc057a-bb70-4dca-91c3-a5c6474c6b75


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

2021-05-16 11:57:55 - Waiting for stack create/update to complete

CloudFormation events from changeset
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ResourceStatus                                        ResourceType                                          LogicalResourceId                                     ResourceStatusReason                                
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE_IN_PROGRESS                                    AWS::IAM::Role                                        HelloWorldFunctionRole                                -                                                   
CREATE_IN_PROGRESS                                    AWS::IAM::Role                                        HelloWorldFunctionRole                                Resource creation Initiated                         
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::ApiGateway::Deployment                           ServerlessRestApiDeployment47fc2d5f9d                 -                                                   
CREATE_COMPLETE                                       AWS::ApiGateway::Deployment                           ServerlessRestApiDeployment47fc2d5f9d                 -                                                   
CREATE_IN_PROGRESS                                    AWS::ApiGateway::Deployment                           ServerlessRestApiDeployment47fc2d5f9d                 Resource creation Initiated                         
CREATE_IN_PROGRESS                                    AWS::Lambda::Permission                               HelloWorldFunctionHelloWorldPermissionProd            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                            portal-sam-app                                        -                                                   
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

CloudFormation outputs from deployed stack
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Outputs                                                                                                                                                                                                                
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Key                 HelloWorldFunctionIamRole                                                                                                                                                                          
Description         Implicit IAM Role created for Hello World function                                                                                                                                                 
Value               arn:aws:iam::45..00:role/portal-sam-app-HelloWorldFunctionRole-1MTYW6WQ67QFV                                                                                                                 

Key                 HelloWorldApi                                                                                                                                                                                      
Description         API Gateway endpoint URL for Prod stage for Hello World function                                                                                                                                   
Value               https://2fmqzej7fg.execute-api.us-west-2.amazonaws.com/Prod/hello/                                                                                                                                 

Key                 HelloWorldFunction                                                                                                                                                                                 
Description         Hello World Lambda Function ARN                                                                                                                                                                    
Value               arn:aws:lambda:us-west-2:45..0:function:portal-sam-app-HelloWorldFunction-iFND1x2c56RQ                                                                                                      
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Successfully created/updated stack - portal-sam-app in us-west-2


test locally
obrienlabs:portal-sam-app m.ien$ sam local start-api
Mounting HelloWorldFunction at http://127.0.0.1:3000/hello [GET]
You can now browse to the above endpoints to invoke your functions. You do not need to restart/reload SAM CLI while working on your functions, changes will be reflected instantly/automatically. You only need to restart SAM CLI if you update your AWS SAM template
2021-05-16 12:08:27  * Running on http://127.0.0.1:3000/ (Press CTRL+C to quit)
2021-05-16 12:08:46 127.0.0.1 - - [16/May/2021 12:08:46] "GET / HTTP/1.1" 403 -


in another terminal

curl http://127.0.0.1:3000/hello
{ "message": "hello world", "location": "175..." }

in the docker container we see
Invoking helloworld.App::handleRequest (java11)
Image was not found.
Building image...............................................................................................................................................................................Invoking helloworld.App::handleRequest (java11)
.Image was not found.
Building image..........................................................................................................................................................................................................................................................................................................................................
Skip pulling image and use local one: amazon/aws-sam-cli-emulation-image-java11:rapid-1.23.0.

Mounting /Users/mi../wse_github/portal-sam-app/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated inside runtime container
...
Skip pulling image and use local one: amazon/aws-sam-cli-emulation-image-java11:rapid-1.23.0.

Mounting /Users/mic...en/wse_github/portal-sam-app/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated inside runtime container
START RequestId: eead621c-ae6c-471f-ba03-a9b3f58ce206 Version: $LATEST
START RequestId: f2f8899c-f48a-445d-8730-9b14d6a283db Version: $LATEST
END RequestId: eead621c-ae6c-471f-ba03-a9b3f58ce206
REPORT RequestId: eead621c-ae6c-471f-ba03-a9b3f58ce206	Init Duration: 0.15 ms	Duration: 1254.51 ms	Billed Duration: 1300 ms	Memory Size: 512 MB	Max Memory Used: 512 MB	
END RequestId: f2f8899c-f48a-445d-8730-9b14d6a283db
REPORT RequestId: f2f8899c-f48a-445d-8730-9b14d6a283db	Init Duration: 0.15 ms	Duration: 1217.77 ms	Billed Duration: 1300 ms	Memory Size: 512 MB	Max Memory Used: 512 MB	
2021-05-16 12:11:41 127.0.0.1 - - [16/May/2021 12:11:41] "GET /hello HTTP/1.1" 200 -


Refreshing a SAM-API local build

sam build

https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-cli-command-reference-sam-build.html

Redeploying a SAM-API change to CloudFormation

sam deploy

curl https://jmyb77m1ra.execute-api.us-west-2.amazonaws.com/Prod/hello/



Rest calls within Lambda via AWS SAM Java API

https://github.com/obrienlabs/refarch/issues/7

Java 11 HttpClient

    // from magellan/RestClient
    private static final String URL_CREATE_RECORD =
            "http://biometric.elasticbeanstalk.com/FrontController?action=latest&u=202107175";

	private void httpClient() {
		HttpClient httpClient = HttpClient.newBuilder().build();
		HttpRequest request = HttpRequest.newBuilder()
				.uri(URI.create(URL_CREATE_RECORD))
				.GET()
				.build();
		try {
			HttpResponse<String> response =
				httpClient.send(request, BodyHandlers.ofString());
			String body = response.body();
			System.out.println("Response: " + body);
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} catch (InterruptedException ie) {
			ie.printStackTrace();
		}
	}

curl https://jmyb77m1ra.execute-api.us-west-2.amazonaws.com/Prod/hello
Response: {
    "tsStop": 1626565987355,
    "tsStart": 1626565987311,
    "sendSeq": 9307,
    "recvSeq": 5825770,
    "heartRate1": null,
    "heartRate2": 79,
    "longitude": -75.707021,
    "lattitude": 45.417048
}


Lambda API


aws lambda list-functions --region=us-west-2
  • No labels

2 Comments

  1. https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install-mac.html

      239  /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

      240  brew version

      241  brew --version

      242  brew tap aws/tap

      243  brew install aws-sam-cli

    obrienlabs:main michaelobrien$ sam --version

    SAM CLI, version 0.34.0

    obrienlabs:main michaelobrien$ sam init


    SAM CLI now collects telemetry to better understand customer needs.


    You can OPT OUT and disable telemetry collection by setting the

    environment variable SAM_CLI_TELEMETRY=0 in your shell.

    Thanks for your help!


    Learn More: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-telemetry.html


    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 - nodejs6.10

    10 - python3.7

    11 - python3.6

    12 - python2.7

    13 - java8

    14 - dotnetcore2.0

    15 - dotnetcore1.0

    Runtime: 8


    Project name [sam-app]:


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


    -----------------------

    Generating application:

    -----------------------

    Name: sam-app

    Runtime: nodejs8.10

    Dependency Manager: npm

    Application Template: hello-world

    Output Directory: .


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



    run

    http://127.0.0.1:3000/hello


    019-11-29 13:54:36 127.0.0.1 - - [29/Nov/2019 13:54:36] "GET / HTTP/1.1" 403 -

    2019-11-29 13:54:36 127.0.0.1 - - [29/Nov/2019 13:54:36] "GET /favicon.ico HTTP/1.1" 403 -

    2019-11-29 13:54:52 127.0.0.1 - - [29/Nov/2019 13:54:52] "GET / HTTP/1.1" 403 -

    Invoking app.lambdaHandler (nodejs8.10)


    Fetching lambci/lambda:nodejs8.10 Docker container image....................................................................................................................................................................................................................................................................................................................................................................................................................................................................

    Mounting /Users/michaelobrien/wse_github/biometric/biometric.web.docker/src/main/sam-app/hello-world as /var/task:ro,delegated inside runtime container

    START RequestId: 7cedd77d-4504-1d3a-594b-fbb77a0cc5fe Version: $LATEST

    END RequestId: 7cedd77d-4504-1d3a-594b-fbb77a0cc5fe

    REPORT RequestId: 7cedd77d-4504-1d3a-594b-fbb77a0cc5fe Init Duration: 149.24 ms Duration: 6.14 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 38 MB

    No Content-Type given. Defaulting to 'application/json'.

    2019-11-29 13:55:56 127.0.0.1 - - [29/Nov/2019 13:55:56] "GET /hello HTTP/1.1" 200 -

    2019-11-29 13:55:56 127.0.0.1 - - [29/Nov/2019 13:55:56] "GET /favicon.ico HTTP/1.1" 403 -



    lambci/lambda                                            nodejs8.10          e1a4867acef5        3 days ago          803MB


  2. cfn fronting sam

      514  sam build

      515  cd upload-portal-api/

      516  sam build

      517  sam build --use-container --cached --build-dir build

      518  sam deploy --guided

      519  history