Upgrade to Pro — share decks privately, control downloads, hide ads and more …

jawsug-hamamatsu_20180825

 jawsug-hamamatsu_20180825

8/25 JAWS-UG浜松 AWS勉強会 2018#1、AWS SAM CLIについての発表資料です。

jacoyutorius

August 25, 2018
Tweet

More Decks by jacoyutorius

Other Decks in Technology

Transcript

  1. AWS SAM CLI & EC2 snapshot by Lambda + CloudWatch

    Events JAWS-UG Hamamatsu @jacoyutorius 2018.8.25
  2. Contents 1. AWS SAM֓ཁͱSAM CLI ͷ࢖͍ํ 2. AWS Lambda &

    CloudWatch Events Ͱ EC2 ͷεφοϓγϣοτ࡞੒
  3. about “SAM CLI” sam local => sam cli - ϓϩδΣΫτσΟϨΫτϦͷॳظԽ

    - DockerΛ༻͍ͨϩʔΧϧ؀ڥͰͷ։ൃ&ςετ؀ڥͷߏங - AWS΁ͷσϓϩΠ ౳ͷػೳ͕SAM CLIͱ͍͏ίϚϯυϥΠϯπʔϧͰఏڙ͞ΕΔɻ 2017.12 ʹΞοϓσʔτɻsam local ͔Β sam cliʹ໊শมߋɻ ͦΕʹ൐͍cliͷػೳ΋େ෯ʹ௥Ճ͞Εͨɻ
  4. $ 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
  5. $ 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
  6. $ 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 ͷςεταϯϓϧ͕ هड़͞Ε͍ͯΔ
  7. $ 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͕τϦΨʔ͞Εͨͱ͖ʹ౉͞ΕΔ֤Πϕϯτͷαϯϓ ϧσʔλΛग़ྗ͢Δ
  8. $ 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
  9. $ 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”౳ͷ໊લͰอଘ͢Δ
  10. $ 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Λ౉͢ɻ
  11. $ 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αʔόʔΛىಈɻ
  12. $ 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 ଆͷϩά
  13. 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 ͷೖྗ಺༰Λݕূ͢Δɻ
  14. 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
  15. $ 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
  16. 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
  17. 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
  18. $ 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
  19. 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
  20. 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)
  21. εέδϡʔϧࣜ cronࣜ cron(0 12 * ** ? *) ຖ೔ޕޙ12:00(UTC)ʹτϦΨʔ͞ΕΔ rateࣜ

    rate(1 day) 1೔͓͖ʹτϦΨʔ͞ΕΔ (https://docs.aws.amazon.com/ja_jp/AmazonCloudWatch/latest/events/ScheduledEvents.html)