Share
Embed
jawsug-hamamatsu_20180825
8/25 JAWS-UG浜松 AWS勉強会 2018#1、AWS SAM CLIについての発表資料です。
jacoyutorius
August 25, 2018
Transcript
39 slides
-
AWS SAM CLI & EC2 snapshot by Lambda + CloudWatch
Events JAWS-UG Hamamatsu @jacoyutorius 2018.8.25 -
Yuto Ogi FOURIER.Inc Ruby, Rails, Javascript, Vue.js, AWS JAWS-UG Hamamatsu,
Hamamatsu.rb @jacoyutoirus -
Contents 1. AWS SAM֓ཁͱSAM CLI ͷ͍ํ 2. AWS Lambda &
CloudWatch Events Ͱ EC2 ͷεφοϓγϣοτ࡞ -
about “SAM CLI” sam local => sam cli - ϓϩδΣΫτσΟϨΫτϦͷॳظԽ
- DockerΛ༻͍ͨϩʔΧϧڥͰͷ։ൃ&ςετڥͷߏங - AWSͷσϓϩΠ ͷػೳ͕SAM CLIͱ͍͏ίϚϯυϥΠϯπʔϧͰఏڙ͞ΕΔɻ 2017.12 ʹΞοϓσʔτɻsam local ͔Β sam cliʹ໊শมߋɻ ͦΕʹ͍cliͷػೳେ෯ʹՃ͞Εͨɻ -
$ sam Usage: sam [OPTIONS] COMMAND [ARGS]... AWS Serverless Application
Model (SAM) CLI Options: --debug Turn on debug logging --version Show the version and exit. --help Show this message and exit. Commands: init Initialize a serverless application with a... package Package an AWS SAM application. This is an alias for 'aws cloudformation package'. local Run your Serverless application locally for... validate Validate an AWS SAM template. deploy Deploy an AWS SAM application. This is an alias for 'aws cloudformation deploy'. commands -
$ sam init —name sample_sam_app [+] Initializing project structure... [SUCCESS]
- Read sample_sam_app/README.md for further instructions on how to proceed [*] Project initialization is now complete $ tree sample_sam_app . ᵓᴷᴷ README.md ᵓᴷᴷ hello_world ᴹ ᵓᴷᴷ app.js ᴹ ᵓᴷᴷ package.json ᴹ ᵋᴷᴷ tests ᴹ ᵋᴷᴷ unit ᴹ ᵋᴷᴷ test_handler.js ᵋᴷᴷ template.yaml 3 directories, 5 files sam init -
$ cd hello_world/ $ yarn install yarn install v0.21.3 [1/4]
Resolving packages... success Already up-to-date. ✨ Done in 0.32s. $ yarn test yarn test v0.21.3 $ mocha tests/unit/ Tests index { statusCode: 200, body: '{"message":"hello world","location":"122.249.204.181"}' } ✓ verifies successful response (682ms) 1 passing (689ms) ✨ Done in 1.38s. unit test Node.jsͷ߹mocha/chai ͷςεταϯϓϧ͕ هड़͞Ε͍ͯΔ -
$ sam local generate-event Usage: sam local generate-event [OPTIONS] COMMAND
[ARGS]... Generate an event Options: --help Show this message and exit. Commands: api ɹGenerates a sample Amazon API Gateway event dynamodb Generates a sample Amazon DynamoDB event kinesis Generates a sample Amazon Kinesis event s3 Generates a sample Amazon S3 event schedule Generates a sample scheduled event sns Generates a sample Amazon SNS event sam local generate-event Lambda͕τϦΨʔ͞Εͨͱ͖ʹ͞ΕΔ֤Πϕϯτͷαϯϓ ϧσʔλΛग़ྗ͢Δ -
$ sam local generate-event api --help Usage: sam local generate-event
api [OPTIONS] Options: -m, --method TEXT HTTP method (default: "POST") -b, --body TEXT HTTP body (default: "{ "test": "body"}") -r, --resource TEXT API Gateway resource name (default: "/{proxy+}") -p, --path TEXT HTTP path (default: "/examplepath") --debug Turn on debug logging --help Show this message and exit. sam local generate-event -
$ sam local generate-event api --method GET { "body": "{
\"test\": \"body\"}", "httpMethod": "GET", "resource": "/{proxy+}", "queryStringParameters": { "foo": "bar" }, "requestContext": { "httpMethod": "GET", "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", "path": "/{proxy+}", "extendedRequestId": null, "resourceId": "123456", "apiId": "1234567890", "stage": "prod", "resourcePath": "/{proxy+}", "identity": { "accountId": null, "apiKey": null, sam local generate-event ίϯιʔϧग़ྗ͞ΕΔͷͰɺ”get_event.json”ͷ໊લͰอଘ͢Δ -
$ sam local invoke HelloWorldFunction --event hello_world/get_event.json 2018-08-20 22:31:05 Invoking
app.lambda_handler (nodejs8.10) 2018-08-20 22:31:05 Found credentials in shared credentials file: ~/.aws/credentials Fetching lambci/lambda:nodejs8.10 Docker container image...... 2018-08-20 22:31:09 Mounting /Users/yuto-ogi/Work/aws_sam/sample_sam_app/hello_world as /var/task:ro insid runtime container START RequestId: 7d55042f-083e-1bac-f3ee-e169c43070ef Version: $LATEST END RequestId: 7d55042f-083e-1bac-f3ee-e169c43070ef REPORT RequestId: 7d55042f-083e-1bac-f3ee-e169c43070ef Duration: 1090.94 ms Billed Duration: 1100 ms Memory Size: 128 MB Max Memory Used: 34 MB {"statusCode":200,"body":"{\"message\":\"hello world\",\"location\":\"126.31.50.151\"}"} sam local invoke ϩʔΧϧͰLambdaΛςετ͢Δɻ--eventʹઌ΄Ͳ࡞ͬͨjsonΛ͢ɻ -
$ sam local start-api 2018-08-20 22:40:53 Mounting HelloWorldFunction at http:/
/127.0.0.1:3000/hello [GET] 2018-08-20 22:40:53 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 2018-08-20 22:40:53 * Running on http:/ /127.0.0.1:3000/ (Press CTRL+C to quit) sam local start-api DockerίϯςφͰAPIαʔόʔΛىಈɻ -
$ curl localhost:3000/hello {"message":"hello world","location":"122.249.204.181"} sam local start-api DockerίϯςφͰAPIαʔόʔΛىಈɻ 2018-08-24
12:57:53 Found credentials in shared credentials file: ~/.aws/credentials Fetching lambci/lambda:nodejs8.10 Docker container image...... 2018-08-24 12:57:57 Mounting /Users/yuto-ogi/Work/aws_sam/sample_sam_app/hello_world as /var/ task:ro inside runtime container START RequestId: 37981056-516e-1742-341b-74ba90730e58 Version: $LATEST END RequestId: 37981056-516e-1742-341b-74ba90730e58 REPORT RequestId: 37981056-516e-1742-341b-74ba90730e58 Duration: 959.08 ms Billed Duration: 1000 ms Memory Size: 128 MB Max Memory Used: 34 MB 2018-08-24 12:58:00 No Content-Type given. Defaulting to 'application/json'. 2018-08-24 12:58:00 127.0.0.1 - - [24/Aug/2018 12:58:00] "GET /hello HTTP/1.1" 200 - sam ଆͷϩά -
sam validate $ sam validate 2018-08-20 22:42:48 Found credentials in
shared credentials file: ~/.aws/credentials 2018-08-20 22:42:48 Starting new HTTPS connection (1): iam.amazonaws.com /Users/yuto-ogi/Work/aws_sam/sample_sam_app/template.yaml is a valid SAM Template template.yaml ͷೖྗ༰Λݕূ͢Δɻ -
sam package $ tree -L 2 . ├── app.js ├──
credentials.json ├── node_modules │ ├── aws-sdk │ ├── base64-js │ ├── buffer │ ├── events │ ├── ieee754 │ ├── isarray │ ├── jmespath │ ├── punycode │ ├── querystring │ ├── sax │ ├── url │ ├── uuid │ ├── xml2js │ └── xmlbuilder ├── package.json └── yarn.lock 15 directories, 4 files -
$ sam package --template-file template.yaml --output-template-file packaged.yaml —s3-bucket yutoogi.sandbox Successfully
packaged artifacts and wrote output template to file packaged.yaml. Execute the following command to deploy the packaged template aws cloudformation deploy --template-file /Users/yuto-ogi/Work/aws_sam/sample_sam_app/ packaged.yaml --stack-name <YOUR STACK NAME> sam package -
AWSTemplateFormatVersion: '2010-09-09' Description: 'sample_sam_app Sample SAM Template for sample_sam_app '
Globals: Function: Timeout: 3 Outputs: HelloWorldApi: Description: API Gateway endpoint URL for Prod stage for Hello World function Value: Fn::Sub: https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/ hello/ HelloWorldFunction: Description: Hello World Lambda Function ARN Value: Fn::GetAtt: - HelloWorldFunction - Arn packaged.yaml -
sam deploy ෦తʹ AWS CLI ͷ “cloudformation” ίϚϯυ͕ݺͼग़͞Ε͍ͯΔ༷ࢠɻ $ sam
deploy usage: aws [options] <command> <subcommand> [<subcommand> ...] [parameters] To see help text, you can run: aws help aws <command> help aws <command> <subcommand> help aws: error: argument --template-file is required -
$ sam deploy --template-file packaged.yaml --stack-name HelloWorldFunction --capabilities CAPABILITY_IAM Waiting
for changeset to be created.. Waiting for stack create/update to complete Successfully created/updated stack - HelloWorldFunction sam deploy -
Resources: AutoSnapshotFunction: Type: AWS::Serverless::Function Properties: CodeUri: auto_snapshot/ Handler: app.lambda_handler Runtime:
nodejs8.10 Environment: Variables: ACCESS_KEY: <YOUR ACCESS KEY> SECRET_ACCESS_KEY: <YOUR SECRET ACCESS KEY> REGION: ap-northeast-1 Events: AutoSnapshot: Type: Schedule Properties: Schedule: cron(10 19 * * ? *) template.yaml -
event source type - S3 - SNS - Kinesis -
DynamoDB - SQS - Api - Schedule - CloudWatchEvent - CloudWatchLogs - IoTRule - AlexaSkill (https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#event-source-types) -
εέδϡʔϧࣜ cronࣜ cron(0 12 * ** ? *) ຖޕޙ12:00(UTC)ʹτϦΨʔ͞ΕΔ rateࣜ
rate(1 day) 1͓͖ʹτϦΨʔ͞ΕΔ (https://docs.aws.amazon.com/ja_jp/AmazonCloudWatch/latest/events/ScheduledEvents.html)