Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save thiagosperandio/d8f3455e5eb25d2c0176f7c8d25cfa31 to your computer and use it in GitHub Desktop.
Save thiagosperandio/d8f3455e5eb25d2c0176f7c8d25cfa31 to your computer and use it in GitHub Desktop.

Criando app HelloWord Java11 com AWS SAM - comandos SAM anotados

Seguindo o tutorial baseado no material da AWS https://docs.aws.amazon.com/pt_br/serverless-application-model/latest/developerguide/serverless-getting-started-hello-world.html

Criando para versão Java 11

Não foi necessário abrir nenhuma IDE ou código para executar este teste

Iniciando um repo com SAM (deu erro)

λ sam init

Deu erro, após todas as configurações selecionadas, quais fossem, chegavam neste ponto:

Cloning from https://github.com/aws/aws-sam-cli-app-templates (process may take a moment)
Error: Unstable state when updating repo. Check that you have permissions to create/delete files in C:\Users\<you>\AppData\Roaming\AWS SAM directory or file an issue at https://github.com/aws/aws-sam-cli/issues

Iniciando um repo com SAM (funcionou)

É necessário escolher o local onde está o template pra gerar o exemplo com SAM, senão dá erro (aws/aws-sam-cli#1891)

λ sam init --location "C:\Users\%username%\AppData\Roaming\AWS SAM\aws-sam-cli-app-templates\java11\cookiecutter-aws-sam-hello-java-maven"

%username% é uma variável do Windows que reconhece o nome do usuário logado. Assim como "%homedrive%%homepath%" dá o caminho padrão "c:\Users\userX" Funcionou:

project_name [Name of the project]: sam-app-java-hello-world
runtime [java11]:
architectures [default]:

Entrar no projeto criado

λ cd sam-app-java-hello-world

Construindo e configurando os artefatos AWS

λ sam build

Resposta:

λ sam build
Your template contains a resource with logical ID "ServerlessRestApi", which is a reserved logical ID in AWS SAM. It could result in unexpected behaviors and is not recommended.
Building codeuri: c:\repos\%username%\aws\sam-tests\sam-app-java-hello-world\HelloWorldFunction runtime: java11 metadata: {} architecture: x86_64 functions: HelloWorldFunction
Running JavaMavenWorkflow:CopySource
Running JavaMavenWorkflow:MavenBuild
Running JavaMavenWorkflow:MavenCopyDependency
Running JavaMavenWorkflow:MavenCopyArtifacts
Running JavaMavenWorkflow:CleanUp
Clean up action: .aws-sam\deps\abf1b74a-52b3-404e-8019-7362c4b1b02b does not exist and will be skipped.
Running JavaMavenWorkflow:JavaCopyDependencies

Build Succeeded

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

Commands you can use next
=========================
[*] Validate SAM template: sam validate
[*] Invoke Function: sam local invoke -t .aws-sam\build\template.yaml
[*] Test Function in the Cloud: sam sync --stack-name {stack-name} --watch
[*] Deploy: sam deploy --guided --template-file .aws-sam\build\template.yaml

Configurações de build e aplicando Cloudformation:

λ sam deploy --guided

Resultado:

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

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

		Setting default arguments for 'sam deploy'
		=========================================
		Stack Name [sam-app]: sam-app-java-hello-world
		AWS Region [us-east-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]:
		#Preserves the state of previously provisioned resources when an operation fails
		Disable rollback [y/N]:
		HelloWorldFunction may not have authorization defined, Is this okay? [y/N]: y
		Save arguments to configuration file [Y/n]:
		SAM configuration file [samconfig.toml]:
		SAM configuration environment [default]:

		Looking for resources needed for deployment:
		Creating the required resources...
		Successfully created!
		 Managed S3 bucket: aws-sam-cli-managed-default-samclisourcebucket-tbrijn2ikufx
		 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 sam-app-java-hello-world/1782288b4f47fd1db4dc2983db7603e9  874663 / 874663  (100.00%)

		Deploying with following values
		===============================
		Stack name                   : sam-app-java-hello-world
		Region                       : us-east-1
		Confirm changeset            : True
		Disable rollback             : False
		Deployment s3 bucket         : aws-sam-cli-managed-default-samclisourcebucket-tbrijn2ikufx
		Capabilities                 : ["CAPABILITY_IAM"]
		Parameter overrides          : {}
		Signing Profiles             : {}

Initiating deployment
=====================
Uploading to sam-app-java-hello-world/ce51a40050ad43e01a6676ac34cea0ae.template  1448 / 1448  (100.00%)

Waiting for changeset to be created..
CloudFormation stack changeset
---------------------------------------------------------------------------------------------------------------------
Operation                     LogicalResourceId             ResourceType                  Replacement
---------------------------------------------------------------------------------------------------------------------
+ Add                         HelloWorldFunctionHelloWorl   AWS::Lambda::Permission       N/A
							  dPermissionProd
+ Add                         HelloWorldFunctionRole        AWS::IAM::Role                N/A
+ Add                         HelloWorldFunction            AWS::Lambda::Function         N/A
+ Add                         ServerlessRestApiDeployment   AWS::ApiGateway::Deployment   N/A
							  47fc2d5f9d
+ Add                         ServerlessRestApiProdStage    AWS::ApiGateway::Stage        N/A
+ Add                         ServerlessRestApi             AWS::ApiGateway::RestApi      N/A
---------------------------------------------------------------------------------------------------------------------

Changeset created successfully. arn:aws:cloudformation:us-east-1:<IAM-id>:changeSet/samcli-deploy1657131838/5a185b72-fb7e-46f1-ae29-10928069bb57


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

2022-07-06 15:25:43 - Waiting for stack create/update to complete

CloudFormation events from stack operations (refresh every 0.5 seconds)
---------------------------------------------------------------------------------------------------------------------
ResourceStatus                ResourceType                  LogicalResourceId             ResourceStatusReason
---------------------------------------------------------------------------------------------------------------------
CREATE_IN_PROGRESS            AWS::IAM::Role                HelloWorldFunctionRole        -
CREATE_IN_PROGRESS            AWS::IAM::Role                HelloWorldFunctionRole        Did not have IAM
																						  permissions to process tags
																						  on AWS::IAM::Role resource.
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       HelloWorldFunctionHelloWorl   -
															dPermissionProd
CREATE_IN_PROGRESS            AWS::ApiGateway::Deployment   ServerlessRestApiDeployment   -
															47fc2d5f9d
CREATE_IN_PROGRESS            AWS::Lambda::Permission       HelloWorldFunctionHelloWorl   Resource creation Initiated
															dPermissionProd
CREATE_IN_PROGRESS            AWS::ApiGateway::Deployment   ServerlessRestApiDeployment   Resource creation Initiated
															47fc2d5f9d
CREATE_COMPLETE               AWS::ApiGateway::Deployment   ServerlessRestApiDeployment   -
															47fc2d5f9d
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       HelloWorldFunctionHelloWorl   -
															dPermissionProd
CREATE_COMPLETE               AWS::CloudFormation::Stack    sam-app-java-hello-world      -
---------------------------------------------------------------------------------------------------------------------
CloudFormation outputs from deployed stack
---------------------------------------------------------------------------------------------------------------------
Outputs
---------------------------------------------------------------------------------------------------------------------
Key                 HelloWorldFunctionIamRole
Description         Implicit IAM Role created for Hello World function
Value               arn:aws:iam::<IAM-id>:role/sam-app-java-hello-world-HelloWorldFunctionRole-1AHSCDN94IZ14

Key                 HelloWorldApi
Description         API Gateway endpoint URL for Prod stage for Hello World function
Value               https://<restapiid-gerada>.execute-api.us-east-1.amazonaws.com/Prod/hello/

Key                 HelloWorldFunction
Description         Hello World Lambda Function ARN
Value               arn:aws:lambda:us-east-1:<IAM-id>:function:sam-app-java-hello-world-HelloWorldFunction-
dN1hUHAKFvhn
---------------------------------------------------------------------------------------------------------------------

Successfully created/updated stack - sam-app-java-hello-world in us-east-1

Testando app criado remotamente:

λ curl https://<restapiid-gerada>.execute-api.us-east-1.amazonaws.com/Prod/hello

Resposta:

{ "message": "hello world", "location": "18.209.47.79" }

Testando app criado localmente:

λ sam local start-api

Resultado do start:

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
2022-07-06 16:28:03  * Running on http://127.0.0.1:3000/ (Press CTRL+C to quit)

Em um segundo prompt chamamos a API local:

λ curl http://127.0.0.1:3000/hello

Resultado:

{ "message": "hello world", "location": "177.11.245.163" }

Neste momento, onde está rodando o sam local start-api (primeiro prompt), é criado um container nomeiado como "rapid images" que serve o app e depois é encerrado, e é informado o que está ocorrendo, como mostrado abaixo:

Invoking helloworld.App::handleRequest (java11)
Image was not found.
Removing rapid images for repo public.ecr.aws/sam/emulation-java11
Building image...................................................................................................................................................................................................................................................................................................................................................................................................................................................
Skip pulling image and use local one: public.ecr.aws/sam/emulation-java11:rapid-1.53.0-x86_64.

Mounting c:\repos\%username%\aws\sam-tests\sam-app-java-hello-world\.aws-sam\build\HelloWorldFunction as /var/task:ro,delegated inside runtime container
START RequestId: a90c780f-524f-46ad-a297-e7a278745401 Version: $LATEST
Picked up JAVA_TOOL_OPTIONS: -XX:+TieredCompilation -XX:TieredStopAtLevel=1
END RequestId: a90c780f-524f-46ad-a297-e7a278745401
REPORT RequestId: a90c780f-524f-46ad-a297-e7a278745401  Init Duration: 0.29 ms  Duration: 3382.11 ms    Billed Duration:
				Memory Size: 512 MB     Max Memory Used: 512 MB
2022-07-06 16:31:16 127.0.0.1 - - [06/Jul/2022 16:31:16] "GET /hello HTTP/1.1" 200 -
Invoking helloworld.App::handleRequest (java11)
Skip pulling image and use local one: public.ecr.aws/sam/emulation-java11:rapid-1.53.0-x86_64.

Mounting c:\repos\%username%\aws\sam-tests\sam-app-java-hello-world\.aws-sam\build\HelloWorldFunction as /var/task:ro,delegated inside runtime container
START RequestId: 86ff45a9-9f58-4a3b-937e-2efccdacf38a Version: $LATEST
Picked up JAVA_TOOL_OPTIONS: -XX:+TieredCompilation -XX:TieredStopAtLevel=1
END RequestId: 86ff45a9-9f58-4a3b-937e-2efccdacf38a
REPORT RequestId: 86ff45a9-9f58-4a3b-937e-2efccdacf38a  Init Duration: 0.33 ms  Duration: 3508.10 ms    Billed Duration:
				Memory Size: 512 MB     Max Memory Used: 512 MB
2022-07-06 16:33:35 127.0.0.1 - - [06/Jul/2022 16:33:35] "GET /hello HTTP/1.1" 200 -
Invoking helloworld.App::handleRequest (java11)
Skip pulling image and use local one: public.ecr.aws/sam/emulation-java11:rapid-1.53.0-x86_64.

Mounting c:\repos\%username%\aws\sam-tests\sam-app-java-hello-world\.aws-sam\build\HelloWorldFunction as /var/task:ro,delegated inside runtime container
START RequestId: 937715e7-ea21-4935-9daf-5f258931b41d Version: $LATEST
Picked up JAVA_TOOL_OPTIONS: -XX:+TieredCompilation -XX:TieredStopAtLevel=1
END RequestId: 937715e7-ea21-4935-9daf-5f258931b41d
REPORT RequestId: 937715e7-ea21-4935-9daf-5f258931b41d  Init Duration: 0.38 ms  Duration: 2621.43 ms    Billed Duration:
				Memory Size: 512 MB     Max Memory Used: 512 MB
2022-07-06 16:34:57 127.0.0.1 - - [06/Jul/2022 16:34:57] "GET /hello HTTP/1.1" 200 -
Invoking helloworld.App::handleRequest (java11)
Skip pulling image and use local one: public.ecr.aws/sam/emulation-java11:rapid-1.53.0-x86_64.

Mounting c:\repos\%username%\aws\sam-tests\sam-app-java-hello-world\.aws-sam\build\HelloWorldFunction as /var/task:ro,delegated inside runtime container
START RequestId: 25f0e151-8ff4-46b2-bbdb-f0da0ab361ec Version: $LATEST
Picked up JAVA_TOOL_OPTIONS: -XX:+TieredCompilation -XX:TieredStopAtLevel=1
END RequestId: 25f0e151-8ff4-46b2-bbdb-f0da0ab361ec
REPORT RequestId: 25f0e151-8ff4-46b2-bbdb-f0da0ab361ec  Init Duration: 0.16 ms  Duration: 3071.72 ms    Billed Duration:
				Memory Size: 512 MB     Max Memory Used: 512 MB
2022-07-06 16:36:20 127.0.0.1 - - [06/Jul/2022 16:36:20] "GET /hello HTTP/1.1" 200 -

Como eu chamei a URL quatro vezes, ele fez "Mounting" quatro vezes, usando uma imagem pronta e recriando o container a cada chamada, simulando um lambda.

Testando app local rodando como um lambda simples diretamente:

λ sam local invoke "HelloWorldFunction" -e events/event.json

Resultado - ele cria o container e já dá o retorno da API, e fecha o container:

Invoking helloworld.App::handleRequest (java11)
Skip pulling image and use local one: public.ecr.aws/sam/emulation-java11:rapid-1.53.0-x86_64.

Mounting c:\repos\%username%\aws\sam-tests\sam-app-java-hello-world\.aws-sam\build\HelloWorldFunction as /var/task:ro,delegated inside runtime container
START RequestId: eb9768f0-8567-41f2-a831-98df60e6a203 Version: $LATEST
Picked up JAVA_TOOL_OPTIONS: -XX:+TieredCompilation -XX:TieredStopAtLevel=1
END RequestId: eb9768f0-8567-41f2-a831-98df60e6a203
REPORT RequestId: eb9768f0-8567-41f2-a831-98df60e6a203  Init Duration: 0.32 ms  Duration: 3500.29 ms    {"statusCode":200,"headers":{"X-eader":"application/jsonMax Memory Used: 512 MBcation/json"},"body":"{ \"message\": \"hello world\", \"location\": \"177.11.245.163\" }"}Memory Size: 512 MB
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment