├── .doc_gen ├── metadata │ ├── serverless_metadata.yaml │ └── services.yaml └── validation.yaml ├── .github ├── CODEOWNERS ├── ISSUE_TEMPLATE │ └── missing-runtime.md ├── scripts │ └── create-pr-from-snippet.js └── workflows │ ├── schema-validation-for-snippet.yml │ └── validate.yml ├── .gitignore ├── ADDING_SNIPPET.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── PUBLISHING.md ├── README.md ├── _snippet-model-multi-files ├── example.js ├── example.py └── snippet-data.json ├── _snippet-model ├── snippet-data.json └── snippet.txt ├── apigateway-dynamodb-crud-simple ├── README.md ├── create-request-body.json ├── getitem-request.json ├── getitem-response.json ├── putitem-request.json ├── read-response-body.json ├── snippet-data.json ├── snippet1-create.txt ├── snippet2-get-request.txt └── snippet3-get-transform.txt ├── apigateway-dynamodb-secure ├── README.md ├── snippet-data.json └── snippet.txt ├── apigateway-dynamodb-typeahead ├── README.md ├── snippet-data.json └── snippet.txt ├── apigw-allow-invoke-only-for-role-and-vpce ├── README.md ├── snippet-data.json └── snippet.txt ├── aws-cli-find-function-runtimes ├── README.md ├── example.txt ├── example2.txt └── snippet-data.json ├── aws-cli-get-cloudformation-outputs ├── README.md ├── snippet-all.txt ├── snippet-data.json └── snippet-specific.txt ├── aws-cli-get-cloudformation-stacks ├── README.md ├── snippet-data.json └── snippet.txt ├── aws-cli-get-functions-in-cloudformation-stack ├── README.md ├── snippet-data.json └── snippet.txt ├── aws-cli-tail-clogwatch-loggroup ├── README.md ├── example.txt └── snippet-data.json ├── aws-cli-update-sam-cloud9 ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-apigw-integration-latency ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-apigw-last-10-requests ├── README copy.md ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-apigw-last-4xx-errors ├── README copy.md ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-apigw-last-5xx-errors ├── README copy.md ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-apigw-longest-running-requests ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-apigw-most-popular-paths ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-apigw-paths-most-4xx ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-apigw-paths-most-5xx ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-apigw-paths-with-most-401-403 ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-apigw-top-10-api-keys ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-apigw-top-10-ips ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-cloudtrail-ec2-hosts-that-start-or-stop-in-aws-region ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-cloudtrail-find-newly-created-users ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-cloudtrail-number-of-entries-for-service-event-region ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-create-latency-report ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-eventbridge-event-by-detail-type-like ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-eventbridge-event-count-by-source ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-eventbridge-event-count ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-eventbridge-event-detail-field-within-a-numeric-range ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-eventbridge-event-filter-by-detail-field-equal-to ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-eventbridge-event-filter-by-detail-field-not-equal-to ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-eventbridge-event-filter-by-detail-type-equal-to ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-eventbridge-event-filter-detail-field-with-values-in-array ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-eventbridge-event-find-if-detail-field-exists ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-eventbridge-event-per-hour ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-eventbridge-event-per-minute ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-eventbridge-event-where-detail-field-value-in ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-eventbridge-event-where-detail-field-value-not-in ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-eventbridge-event-where-value-equals-nested-detail-field-value ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-eventbridge-event-with-detail-field-empty ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-exception-per-hour ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-lambda-100-highest-billed-invocations ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-lambda-average-memory-across-invocations ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-lambda-cold-start-invocations-byfunction ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-lambda-cold-start-invocations ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-lambda-cold-starts-count-and-duration ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-lambda-invocation-where-lambda-exited ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-lambda-invocations-timed-out ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-lambda-last-100-errors ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-lambda-max-assigned-memory ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-lambda-memory-debugger ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-lambda-percentile-duration-report ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-lambda-percentile-memory-report ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-lambda-total-innvocations-vs-coldstarts ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-lambda-visualization-of-memory-statisitcs ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-lambda-warm-starts ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-overprovisioned-memory-for-lambda ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-recently-added-logs ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-route53-distribution-of-records-per-hours ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-route53-dns-resolvers-with-highest-request ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-vpc-top-15-byte-transfers ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-insight-vpc-top-15-packet-transfers ├── README.md ├── snippet-data.json └── snippet.txt ├── cloudwatch-logs-that-are-not-exceptions ├── README.md ├── snippet-data.json └── snippet.txt ├── http-api-parameter-mapping-for-remove-action ├── README.md ├── snippet-data.json └── snippet.txt ├── images ├── multi-snippet.png ├── single-snippet.png └── tabbed-snippet.png ├── integration-ddb-to-lambda-with-batch-item-handling ├── Function.cs ├── example.go ├── example.java ├── example.js ├── example.php ├── example.py ├── example.rb ├── example.ts └── main.rs ├── integration-ddb-to-lambda ├── Function.cs ├── example.go ├── example.java ├── example.js ├── example.php ├── example.py ├── example.rb ├── example.rs └── example.ts ├── integration-docdb-to-lambda ├── Example.java ├── Function.cs ├── example.js ├── example.php ├── example.py ├── example.rb ├── example.rs ├── example.ts ├── main.go └── snippet-data.json ├── integration-kinesis-to-lambda-with-batch-item-handling ├── Function.cs ├── README.md ├── example.go ├── example.java ├── example.js ├── example.php ├── example.py ├── example.rb ├── example.ts ├── main.rs └── snippet-data.json ├── integration-kinesis-to-lambda ├── Function.cs ├── Handler.java ├── README.md ├── example.js ├── example.php ├── example.rb ├── example.ts ├── main.go ├── main.py ├── main.rs └── snippet-data.json ├── integration-msk-to-lambda ├── Example.java ├── Function.cs ├── example.go ├── example.js ├── example.php ├── example.py ├── example.rb ├── example.ts └── main.rs ├── integration-s3-to-lambda ├── Function.cs ├── Handler.java ├── README.md ├── example.js ├── example.php ├── example.py ├── example.rb ├── example.ts ├── main.go ├── main.rs └── snippet-data.json ├── integration-sns-to-lambda ├── Function.cs ├── README.md ├── SNSEventHandler.java ├── example.go ├── example.js ├── example.php ├── example.py ├── example.rb ├── example.ts ├── lambda-sns-receive.rs └── snippet-data.json ├── integration-sqs-to-lambda-with-batch-item-handling ├── Function.cs ├── README.md ├── example.js ├── example.rb ├── example.ts └── snippet-data.json ├── integration-sqs-to-lambda ├── Function.cs ├── Function.go ├── Function.java ├── Function.py ├── Function.rb ├── README.md ├── example.js ├── example.php ├── example.ts ├── main.rs └── snippet-data.json ├── lambda-connect-opensearch ├── README.md ├── main.go └── snippet-data.json ├── lambda-edge-list-functions ├── README.md ├── snippet-data.json └── snippet.txt ├── lambda-function-connect-memorydb-iam ├── README.md ├── example.java ├── example.ts └── snippet-data.json ├── lambda-function-connect-rds-iam ├── README.md ├── example.cs ├── example.java ├── example.js ├── example.php ├── example.py ├── example.ts ├── lambda_function.rb ├── main.go ├── main.rs └── snippet-data.json ├── lambda-function-convert-s3-storageclass ├── README.md ├── snippet-data.json └── snippet.txt ├── lambda-function-invoke-vpc-lattice-service ├── README.md ├── example.ts └── snippet-data.json ├── lambda-function-kafka-consumer-glue-schema-registry ├── README.md ├── example.py └── snippet-data.json ├── lambda-function-retrieve-deleted-s3-versioned-objects ├── README.md ├── snippet-data.json └── snippet.txt ├── lambda-function-sqs-report-batch-item-failures ├── README.md ├── example.cs ├── example.go ├── example.java ├── example.mjs ├── example.php ├── example.py ├── example.rs ├── example.ts └── snippet-data.json ├── lambda-function-throwing-errors ├── README.md ├── snippet-data.json └── snippet.txt ├── restrict-deployment-to-apigw-stage ├── README.md ├── snippet-data.json └── snippet.txt ├── scripts ├── create.js ├── package.json ├── schema.json ├── snippet.txt ├── template │ ├── README.md │ └── snippet-data.json └── validate.js ├── serverlessland.png ├── snippets.png ├── stepfunctions-intrinsic-function-getYYMMfromContext ├── README.md ├── snippet-data.json └── snippet.txt ├── tools-powertools-logger ├── Function.cs ├── LoggingHandler.java ├── README.md ├── powertools-logger.ts └── snippet-data.json ├── tools-powertools-metrics ├── Function.cs ├── MetricsHandler.java ├── README.md ├── powertools-metrics.ts └── snippet-data.json ├── tools-powertools-tracing ├── Function.cs ├── README.md ├── TracingHandler.java └── snippet-data.json └── vpc-subnets-serverless ├── README.md ├── snippet-data.json └── snippet.txt /.doc_gen/metadata/services.yaml: -------------------------------------------------------------------------------- 1 | serverless: 2 | long: "&Serverless;" 3 | short: "&Serverless;" 4 | sort: Serverless 5 | expanded: 6 | long: Serverless Examples 7 | short: Serverless 8 | blurb: used for Serverless Development. 9 | guide: 10 | subtitle: User Guide 11 | tags: 12 | product_categories: { "Serverless" } 13 | version: 1 14 | -------------------------------------------------------------------------------- /.doc_gen/validation.yaml: -------------------------------------------------------------------------------- 1 | allow_list: 2 | - "com/apigateway/latest/developerguide/set" 3 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | @boyney123 @yualexan 2 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/missing-runtime.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: New serverless runtime submission 3 | about: Missing runtime for a snippet 4 | title: Missing runtime for snippet 5 | labels: '' 6 | assignees: boyney123 7 | --- 8 | 9 | Please let us know what runtime you would like to see in the example snippet. We will collect the feedback and create an example in the requested runtime. 10 | -------------------------------------------------------------------------------- /.github/workflows/schema-validation-for-snippet.yml: -------------------------------------------------------------------------------- 1 | name: "Schema Validation" 2 | 3 | on: [pull_request] 4 | 5 | jobs: 6 | validate-pattern: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - name: Checkout code 10 | uses: actions/checkout@v3 11 | 12 | - uses: actions/setup-node@v3 13 | with: 14 | node-version: 16 15 | 16 | - name: Get changed files using defaults 17 | id: changed-files 18 | uses: tj-actions/changed-files@df3e9932c48cda43e6e09567f3a1ce1b38ca76e9 19 | with: 20 | separator: "," 21 | 22 | - run: cd scripts && npm i 23 | 24 | - name: Validate 25 | run: node scripts/validate.js 26 | env: # Or as an environment variable 27 | MODIFIED_FILES: ${{ steps.changed-files.outputs.modified_files }} 28 | ADDED_FILES: ${{ steps.changed-files.outputs.added_files }} 29 | PR_NUMBER: ${{ github.event.number }} 30 | GH_AUTOMATION: false -------------------------------------------------------------------------------- /.github/workflows/validate.yml: -------------------------------------------------------------------------------- 1 | # Run Python checkin script on push or pull request 2 | name: Snippet & Repo Validation Checks 3 | 4 | # Controls when the action will run. 5 | on: 6 | # Triggers the workflow on push or pull request events but only for the main branch 7 | push: 8 | branches: [main] 9 | pull_request: 10 | branches: [main] 11 | 12 | # Allows you to run this workflow manually from the Actions tab 13 | workflow_dispatch: 14 | 15 | # A workflow run is made up of one or more jobs that can run sequentially or in parallel 16 | jobs: 17 | # This workflow contains a single job called "build" 18 | validate: 19 | # The type of runner that the job will run on 20 | runs-on: ubuntu-latest 21 | 22 | # Steps represent a sequence of tasks that will be executed as part of the job 23 | steps: 24 | - name: checkout repo content 25 | uses: actions/checkout@v3 # checkout the repository content to github runner. 26 | - name: validate metadata 27 | uses: awsdocs/aws-doc-sdk-examples-tools@main 28 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | ## Code of Conduct 2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 4 | opensource-codeofconduct@amazon.com with any additional questions or comments. 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of 4 | this software and associated documentation files (the "Software"), to deal in 5 | the Software without restriction, including without limitation the rights to 6 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software is furnished to do so. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 10 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 11 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 12 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 13 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 14 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 15 | 16 | -------------------------------------------------------------------------------- /_snippet-model-multi-files/example.js: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | const aws = require('aws-sdk'); 4 | 5 | const s3 = new aws.S3({ apiVersion: '2006-03-01' }); 6 | 7 | exports.handler = async (event, context) => { 8 | // Get the object from the event and show its content type 9 | const bucket = event.Records[0].s3.bucket.name; 10 | const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); 11 | const params = { 12 | Bucket: bucket, 13 | Key: key, 14 | }; 15 | try { 16 | const { ContentType } = await s3.getObject(params).promise(); 17 | console.log('CONTENT TYPE:', ContentType); 18 | return ContentType; 19 | } catch (err) { 20 | console.log(err); 21 | const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`; 22 | console.log(message); 23 | throw new Error(message); 24 | } 25 | }; -------------------------------------------------------------------------------- /_snippet-model-multi-files/example.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: Apache-2.0 3 | import json 4 | import urllib.parse 5 | import boto3 6 | 7 | print('Loading function') 8 | 9 | s3 = boto3.client('s3') 10 | 11 | 12 | def lambda_handler(event, context): 13 | #print("Received event: " + json.dumps(event, indent=2)) 14 | 15 | # Get the object from the event and show its content type 16 | bucket = event['Records'][0]['s3']['bucket']['name'] 17 | key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8') 18 | try: 19 | response = s3.get_object(Bucket=bucket, Key=key) 20 | print("CONTENT TYPE: " + response['ContentType']) 21 | return response['ContentType'] 22 | except Exception as e: 23 | print(e) 24 | print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket)) 25 | raise e 26 | -------------------------------------------------------------------------------- /_snippet-model/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "[[your title]]", 3 | "description": "[[ your description ]]", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["lambda"], 6 | "tags": [], 7 | "languages": [], 8 | "introBox": { 9 | "headline": "How it works", 10 | "text": [ 11 | "[[description of how the snippet works]]" 12 | ] 13 | }, 14 | "gitHub": { 15 | "template": { 16 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-exception-per-hour" 17 | } 18 | }, 19 | "snippets": [ 20 | { 21 | "title": "Copy the code into CloudWatch Logs Insights", 22 | "snippetPath": "snippet.txt", 23 | "language": "css" // use css for cloudwatch (looks good), or find your language from https://prismjs.com/#languages-list 24 | } 25 | ], 26 | "authors": [ 27 | { 28 | "headline": "Presented by [[your name]]", 29 | "name": "[[your name]]", 30 | "image": "link-to-your-photo.jpg", 31 | "bio": "Your bio", 32 | "linkedin": "linked-in-ID", 33 | "twitter": "twitter-handle" 34 | } 35 | ] 36 | } 37 | -------------------------------------------------------------------------------- /_snippet-model/snippet.txt: -------------------------------------------------------------------------------- 1 | filter @message like /Exception/ 2 | | stats count(*) as exceptionCount by bin(1h) 3 | | sort exceptionCount desc -------------------------------------------------------------------------------- /apigateway-dynamodb-crud-simple/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /apigateway-dynamodb-crud-simple/create-request-body.json: -------------------------------------------------------------------------------- 1 | { 2 | "partitionkey": "item123", 3 | "timestamp": "2015-12-21T17:42:34Z", 4 | "binary": "dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk", 5 | "boolean": "true", 6 | "null": "null", 7 | "number": "1437136300" 8 | } -------------------------------------------------------------------------------- /apigateway-dynamodb-crud-simple/getitem-request.json: -------------------------------------------------------------------------------- 1 | { 2 | "TableName": "SimpleTable1", 3 | "Key": { 4 | "partitionkey": { 5 | "S": "item123" 6 | } 7 | } 8 | } -------------------------------------------------------------------------------- /apigateway-dynamodb-crud-simple/getitem-response.json: -------------------------------------------------------------------------------- 1 | { 2 | "Item": { 3 | "partitionkey": { 4 | "S": "item123" 5 | }, 6 | "number": { 7 | "S": "1437136300" 8 | }, 9 | "timestamp": { 10 | "S": "2015-12-21T17:42:34Z" 11 | }, 12 | "null": { 13 | "S": "null" 14 | }, 15 | "boolean": { 16 | "S": "true" 17 | }, 18 | "binary": { 19 | "S": "dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk" 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /apigateway-dynamodb-crud-simple/putitem-request.json: -------------------------------------------------------------------------------- 1 | { 2 | "TableName": "SimpleTable1", 3 | "Item": { 4 | "partitionkey": { 5 | "S": "item123" 6 | }, 7 | "timestamp": { 8 | "S": "2015-12-21T17:42:34Z" 9 | }, 10 | "binary": { 11 | "S": "dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk" 12 | }, 13 | "boolean": { 14 | "S": "true" 15 | }, 16 | "null": { 17 | "S": "null" 18 | }, 19 | "number": { 20 | "S": "1437136300" 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /apigateway-dynamodb-crud-simple/read-response-body.json: -------------------------------------------------------------------------------- 1 | { 2 | "partitionkey": "item123", 3 | "timestamp": "2015-12-21T17:42:34Z", 4 | "binary": "dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk", 5 | "boolean": "true", 6 | "null": "null", 7 | "number": "1437136300" 8 | } -------------------------------------------------------------------------------- /apigateway-dynamodb-crud-simple/snippet1-create.txt: -------------------------------------------------------------------------------- 1 | #set ($body-objects = $util.parseJson($input.json('$'))) 2 | #set ($body-objects.partitionkey = $input.params('stringkey')) 3 | { 4 | "TableName": "SimpleTable1", 5 | "Item" : { 6 | #foreach($mapEntry in $body-objects.entrySet()) 7 | "$mapEntry.key" : {"S": "$util.escapeJavaScript( $mapEntry.value)"} 8 | #if($foreach.hasNext),#end 9 | #end 10 | } 11 | } -------------------------------------------------------------------------------- /apigateway-dynamodb-crud-simple/snippet2-get-request.txt: -------------------------------------------------------------------------------- 1 | { 2 | "TableName": "SimpleTable1", 3 | "Key": { 4 | "partitionkey": {"S": "$input.params('stringkey')"} 5 | } 6 | } -------------------------------------------------------------------------------- /apigateway-dynamodb-crud-simple/snippet3-get-transform.txt: -------------------------------------------------------------------------------- 1 | #set($responseData = $input.path('$.Item')) 2 | {#foreach($mapEntry in $responseData.entrySet()) 3 | "$mapEntry.key": "$mapEntry.value.get("S")"## 4 | #if($foreach.hasNext),#end## 5 | #end 6 | } -------------------------------------------------------------------------------- /apigateway-dynamodb-secure/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /apigateway-dynamodb-secure/snippet.txt: -------------------------------------------------------------------------------- 1 | #set( $pageKey = $input.params('pageKey')) 2 | { 3 | "TableName": "myTable", 4 | "IndexName":"OwnerIndex", 5 | "KeyConditionExpression": "#n_owner = :v_owner", 6 | "ExpressionAttributeValues": { 7 | ":v_owner": {"S": "$context.authorizer.claims.email"} 8 | }, 9 | "ExpressionAttributeNames": {"#n_owner": "owner"} 10 | } -------------------------------------------------------------------------------- /apigateway-dynamodb-typeahead/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /apigateway-dynamodb-typeahead/snippet.txt: -------------------------------------------------------------------------------- 1 | #set( $pageKey = $input.params('pageKey')) 2 | { 3 | "TableName": "myTable", 4 | "IndexName":"OwnerIndex", 5 | "KeyConditionExpression": "#n_owner = :v_owner", 6 | "FilterExpression": "contains(#n_id, :v_searchString)", 7 | "ExpressionAttributeValues": { 8 | ":v_owner": {"S": "$context.authorizer.claims.email"}, 9 | ":v_searchString":{"S":"$input.params().path.searchString"} 10 | }, 11 | "ExpressionAttributeNames": {"#n_owner": "owner", "#n_id":"id"} 12 | } -------------------------------------------------------------------------------- /apigw-allow-invoke-only-for-role-and-vpce/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /apigw-allow-invoke-only-for-role-and-vpce/snippet.txt: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Effect": "Allow", 6 | "Principal": { 7 | "AWS": "arn:aws:iam:::role/" 8 | }, 9 | "Action": "execute-api:Invoke", 10 | "Resource": "arn:aws:execute-api:us-east-1::/*" 11 | }, 12 | { 13 | "Effect": "Deny", 14 | "Principal": { 15 | "AWS": "arn:aws:iam:::role/" 16 | }, 17 | "Action": "execute-api:Invoke", 18 | "Resource": "arn:aws:execute-api:us-east-1::/*", 19 | "Condition": { 20 | "StringNotEquals": { 21 | "aws:SourceVpce": "" 22 | } 23 | } 24 | }, 25 | { 26 | "Effect": "Deny", 27 | "Principal": { 28 | "AWS": "*" 29 | }, 30 | "Action": "execute-api:Invoke", 31 | "Resource": "arn:aws:execute-api:us-east-1::/*", 32 | "Condition": { 33 | "StringNotEquals": { 34 | "aws:PrincipalArn": "arn:aws:iam:::role/" 35 | } 36 | } 37 | } 38 | ] 39 | } 40 | -------------------------------------------------------------------------------- /aws-cli-find-function-runtimes/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /aws-cli-find-function-runtimes/example.txt: -------------------------------------------------------------------------------- 1 | aws lambda list-functions --function-version ALL --output text --query "Functions[?Runtime=='python2.7'].FunctionArn" -------------------------------------------------------------------------------- /aws-cli-find-function-runtimes/example2.txt: -------------------------------------------------------------------------------- 1 | for region in `aws ec2 describe-regions --query "Regions[].RegionName" --region us-west-1 --output text` 2 | do 3 | echo "[${region}]" 4 | aws lambda list-functions --region ${region} --output text --query "Functions[?Runtime=='python2.7'].{ARN:FunctionArn, Runtime:Runtime}" 5 | done 6 | echo "finished" -------------------------------------------------------------------------------- /aws-cli-get-cloudformation-outputs/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /aws-cli-get-cloudformation-outputs/snippet-all.txt: -------------------------------------------------------------------------------- 1 | aws cloudformation describe-stacks --stack-name --query "Stacks[*].Outputs[*].{OutputKey: OutputKey, OutputValue: OutputValue, Description: Description}" -------------------------------------------------------------------------------- /aws-cli-get-cloudformation-outputs/snippet-specific.txt: -------------------------------------------------------------------------------- 1 | aws cloudformation describe-stacks --stack-name --query "Stacks[*].Outputs[*].{OutputKey: OutputKey, OutputValue: OutputValue, Description: Description}" -------------------------------------------------------------------------------- /aws-cli-get-cloudformation-stacks/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /aws-cli-get-cloudformation-stacks/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "List CloudFormation Stacks", 3 | "description": "An AWS CLI command to list all CloudFormation Stacks and a query to show how to only show StackId and StackName", 4 | "type": "AWS CLI", 5 | "services": ["CloudFormation"], 6 | "languages": ["aws cli"], 7 | "tags": ["debugging"], 8 | "introBox": { 9 | "headline": "How it works", 10 | "text": ["An AWS CLI command that retrieves all the stacks from CloudFormation and outputs them. The optional query parameter limits the output of the command so that only the StackIs and the StackName are returned."] 11 | }, 12 | "gitHub": { 13 | "template": { 14 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/aws-cli-get-cloudformation-stacks" 15 | } 16 | }, 17 | "snippets": [ 18 | { 19 | "snippetPath": "snippet.txt", 20 | "language": "aws cli" 21 | } 22 | ], 23 | "authors": [ 24 | { 25 | "headline": "Hopefully something useful from Paul Johnston", 26 | "name": "Paul Johnston", 27 | "image": "https://pbs.twimg.com/profile_images/1489994130004533259/gz6LI1oW_400x400.jpg", 28 | "bio": "CTO, Consultant, Interim and Strategist (and ex-Serverless Developer Advocate at AWS)", 29 | "linkedin": "https://www.linkedin.com/in/padajo/", 30 | "twitter": "PaulDJohnston" 31 | } 32 | ] 33 | } 34 | -------------------------------------------------------------------------------- /aws-cli-get-cloudformation-stacks/snippet.txt: -------------------------------------------------------------------------------- 1 | aws cloudformation list-stacks 2 | or 3 | aws cloudformation list-stacks --query "StackSummaries[*].{StackId: StackId, StackName: StackName}" -------------------------------------------------------------------------------- /aws-cli-get-functions-in-cloudformation-stack/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /aws-cli-get-functions-in-cloudformation-stack/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Get Lambda Functions in a CloudFormation Stack", 3 | "description": "An AWS CLI command to retrieve all AWS Lambda function resources in a named CloudFormation Stack", 4 | "type": "AWS CLI", 5 | "services": ["lambda", "CloudFormation"], 6 | "languages": ["aws cli"], 7 | "tags": ["debugging"], 8 | "introBox": { 9 | "headline": "How it works", 10 | "text": ["AWS CLI command that retrieves all the resources in a CloudFormation stack and queries the returned data for ResourceType of 'AWS::Lambda::Function'"] 11 | }, 12 | "gitHub": { 13 | "template": { 14 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/aws-cli-get-functions-in-cloudformation-stack" 15 | } 16 | }, 17 | "snippets": [ 18 | { 19 | "snippetPath": "snippet.txt", 20 | "language": "aws cli" 21 | } 22 | ], 23 | "authors": [ 24 | { 25 | "headline": "Hopefully something useful from Paul Johnston", 26 | "name": "Paul Johnston", 27 | "image": "https://pbs.twimg.com/profile_images/1489994130004533259/gz6LI1oW_400x400.jpg", 28 | "bio": "CTO, Consultant, Interim and Strategist (and ex-Serverless Developer Advocate at AWS)", 29 | "linkedin": "https://www.linkedin.com/in/padajo/", 30 | "twitter": "PaulDJohnston" 31 | } 32 | ] 33 | } 34 | -------------------------------------------------------------------------------- /aws-cli-get-functions-in-cloudformation-stack/snippet.txt: -------------------------------------------------------------------------------- 1 | aws cloudformation list-stack-resources --stack-name (stack id) --query "StackResourceSummaries[?ResourceType=='AWS::Lambda::Function'].{LogicalResourceId: LogicalResourceId, PhysicalResourceId: PhysicalResourceId, LastUpdate: LastUpdatedTimestamp}" -------------------------------------------------------------------------------- /aws-cli-tail-clogwatch-loggroup/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /aws-cli-tail-clogwatch-loggroup/example.txt: -------------------------------------------------------------------------------- 1 | 2022-10-05T08:32:51+00:00 f525e7be-c42d-3f0d-a7c4-6a51d01da714 2 | { 3 | "version": "0", 4 | "id": "daf8f653-560e-df19-c0d7-441cb55c414a", 5 | "detail-type": "UserCreated", 6 | "source": "com.mycompany.myapp", 7 | "account": "123456789123", 8 | "time": "2022-10-05T08:32:51Z", 9 | "region": "us-west-2", 10 | "resources": [ 11 | "resource1", 12 | "resource2" 13 | ], 14 | "detail": { 15 | "key1": "value1", 16 | "key2": "value2" 17 | } 18 | } 19 | 2022-10-05T08:33:05+00:00 c996a3cc-dd68-3aef-9fbb-6a2c7f8e4472 20 | { 21 | "version": "0", 22 | "id": "3b256c05-8879-e7f5-94be-ce3bc7af68f4", 23 | "detail-type": "UserCreated", 24 | "source": "com.mycompany.myapp", 25 | "account": "123456789123", 26 | "time": "2022-10-05T08:33:05Z", 27 | "region": "us-west-2", 28 | "resources": [ 29 | "resource1", 30 | "resource2" 31 | ], 32 | "detail": { 33 | "key1": "value1", 34 | "key2": "value2" 35 | } 36 | } -------------------------------------------------------------------------------- /aws-cli-update-sam-cloud9/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /aws-cli-update-sam-cloud9/snippet.txt: -------------------------------------------------------------------------------- 1 | sudo yum update -y 2 | wget https://github.com/aws/aws-sam-cli/releases/latest/download/aws-sam-cli-linux-x86_64.zip 3 | unzip aws-sam-cli-linux-x86_64.zip -d sam-installation 4 | sudo ./sam-installation/install --update 5 | sam --version -------------------------------------------------------------------------------- /cloudwatch-insight-apigw-integration-latency/README.md: -------------------------------------------------------------------------------- 1 | ## Amazon API Gateway Access Logging Setup 2 | 3 | This snippet assumes that Amazon API Gateway logs requests to Amazon CloudWatch Logs using JSON and the following log format: 4 | 5 | ```json 6 | { 7 | "requestId":"$context.requestId", 8 | "ip": "$context.identity.sourceIp", 9 | "apiKey": "$context.identity.apiKey", 10 | "requestTime":"$context.requestTime", 11 | "httpMethod":"$context.httpMethod", 12 | "routeKey":"$context.routeKey", 13 | "path":"$context.path", 14 | "status": $context.status, 15 | "protocol":"$context.protocol", 16 | "integrationStatus": $context.integrationStatus, 17 | "integrationLatency": $context.integrationLatency, 18 | "responseLatency":$context.responseLatency, 19 | "responseLength": $context.responseLength 20 | } 21 | ``` 22 | 23 | You can modify log format to fit your needs (make sure to update code snippet if field names change). 24 | 25 | 26 | See documentation for more details on how to set up API Gateway logging in HTTP (https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-logging.html) and REST (https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-logging.html) APIs. -------------------------------------------------------------------------------- /cloudwatch-insight-apigw-integration-latency/snippet.txt: -------------------------------------------------------------------------------- 1 | filter status=200 2 | | stats avg(integrationLatency), max(integrationLatency), 3 | min(integrationLatency) by bin(1m) -------------------------------------------------------------------------------- /cloudwatch-insight-apigw-last-10-requests/README copy.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-apigw-last-10-requests/README.md: -------------------------------------------------------------------------------- 1 | ## Amazon API Gateway Access Logging Setup 2 | 3 | This snippet assumes that Amazon API Gateway logs requests to Amazon CloudWatch Logs using JSON and the following log format: 4 | 5 | ```json 6 | { 7 | "requestId":"$context.requestId", 8 | "ip": "$context.identity.sourceIp", 9 | "apiKey": "$context.identity.apiKey", 10 | "requestTime":"$context.requestTime", 11 | "httpMethod":"$context.httpMethod", 12 | "routeKey":"$context.routeKey", 13 | "path":"$context.path", 14 | "status": $context.status, 15 | "protocol":"$context.protocol", 16 | "integrationStatus": $context.integrationStatus, 17 | "integrationLatency": $context.integrationLatency, 18 | "responseLatency":$context.responseLatency, 19 | "responseLength": $context.responseLength 20 | } 21 | ``` 22 | 23 | You can modify log format to fit your needs (make sure to update code snippet if field names change). 24 | 25 | 26 | See documentation for more details on how to set up API Gateway logging in HTTP (https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-logging.html) and REST (https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-logging.html) APIs. -------------------------------------------------------------------------------- /cloudwatch-insight-apigw-last-10-requests/snippet.txt: -------------------------------------------------------------------------------- 1 | fields @timestamp, status, ip, path, httpMethod 2 | | sort @timestamp desc 3 | | limit 10 -------------------------------------------------------------------------------- /cloudwatch-insight-apigw-last-4xx-errors/README copy.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-apigw-last-4xx-errors/README.md: -------------------------------------------------------------------------------- 1 | ## Amazon API Gateway Access Logging Setup 2 | 3 | This snippet assumes that Amazon API Gateway logs requests to Amazon CloudWatch Logs using JSON and the following log format: 4 | 5 | ```json 6 | { 7 | "requestId":"$context.requestId", 8 | "ip": "$context.identity.sourceIp", 9 | "apiKey": "$context.identity.apiKey", 10 | "requestTime":"$context.requestTime", 11 | "httpMethod":"$context.httpMethod", 12 | "routeKey":"$context.routeKey", 13 | "path":"$context.path", 14 | "status": $context.status, 15 | "protocol":"$context.protocol", 16 | "integrationStatus": $context.integrationStatus, 17 | "integrationLatency": $context.integrationLatency, 18 | "responseLatency":$context.responseLatency, 19 | "responseLength": $context.responseLength 20 | } 21 | ``` 22 | 23 | You can modify log format to fit your needs (make sure to update code snippet if field names change). 24 | 25 | 26 | See documentation for more details on how to set up API Gateway logging in HTTP (https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-logging.html) and REST (https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-logging.html) APIs. -------------------------------------------------------------------------------- /cloudwatch-insight-apigw-last-4xx-errors/snippet.txt: -------------------------------------------------------------------------------- 1 | fields @timestamp, status, ip, path, httpMethod 2 | | filter status>=400 and status<=499 3 | | sort @timestamp desc 4 | | limit 10 -------------------------------------------------------------------------------- /cloudwatch-insight-apigw-last-5xx-errors/README copy.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-apigw-last-5xx-errors/README.md: -------------------------------------------------------------------------------- 1 | ## Amazon API Gateway Access Logging Setup 2 | 3 | This snippet assumes that Amazon API Gateway logs requests to Amazon CloudWatch Logs using JSON and the following log format: 4 | 5 | ```json 6 | { 7 | "requestId":"$context.requestId", 8 | "ip": "$context.identity.sourceIp", 9 | "apiKey": "$context.identity.apiKey", 10 | "requestTime":"$context.requestTime", 11 | "httpMethod":"$context.httpMethod", 12 | "routeKey":"$context.routeKey", 13 | "path":"$context.path", 14 | "status": $context.status, 15 | "protocol":"$context.protocol", 16 | "integrationStatus": $context.integrationStatus, 17 | "integrationLatency": $context.integrationLatency, 18 | "responseLatency":$context.responseLatency, 19 | "responseLength": $context.responseLength 20 | } 21 | ``` 22 | 23 | You can modify log format to fit your needs (make sure to update code snippet if field names change). 24 | 25 | 26 | See documentation for more details on how to set up API Gateway logging in HTTP (https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-logging.html) and REST (https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-logging.html) APIs. -------------------------------------------------------------------------------- /cloudwatch-insight-apigw-last-5xx-errors/snippet.txt: -------------------------------------------------------------------------------- 1 | fields @timestamp, status, ip, path, httpMethod 2 | | filter status>=500 and status<=599 3 | | sort @timestamp desc 4 | | limit 10 -------------------------------------------------------------------------------- /cloudwatch-insight-apigw-longest-running-requests/README.md: -------------------------------------------------------------------------------- 1 | ## Amazon API Gateway Access Logging Setup 2 | 3 | This snippet assumes that Amazon API Gateway logs requests to Amazon CloudWatch Logs using JSON and the following log format: 4 | 5 | ```json 6 | { 7 | "requestId":"$context.requestId", 8 | "ip": "$context.identity.sourceIp", 9 | "apiKey": "$context.identity.apiKey", 10 | "requestTime":"$context.requestTime", 11 | "httpMethod":"$context.httpMethod", 12 | "routeKey":"$context.routeKey", 13 | "path":"$context.path", 14 | "status": $context.status, 15 | "protocol":"$context.protocol", 16 | "integrationStatus": $context.integrationStatus, 17 | "integrationLatency": $context.integrationLatency, 18 | "responseLatency":$context.responseLatency, 19 | "responseLength": $context.responseLength 20 | } 21 | ``` 22 | 23 | You can modify log format to fit your needs (make sure to update code snippet if field names change). 24 | 25 | 26 | See documentation for more details on how to set up API Gateway logging in HTTP (https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-logging.html) and REST (https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-logging.html) APIs. -------------------------------------------------------------------------------- /cloudwatch-insight-apigw-longest-running-requests/snippet.txt: -------------------------------------------------------------------------------- 1 | fields @timestamp, status, ip, path, httpMethod, responseLatency 2 | | sort responseLatency desc 3 | | limit 10 -------------------------------------------------------------------------------- /cloudwatch-insight-apigw-most-popular-paths/README.md: -------------------------------------------------------------------------------- 1 | ## Amazon API Gateway Access Logging Setup 2 | 3 | This snippet assumes that Amazon API Gateway logs requests to Amazon CloudWatch Logs using JSON and the following log format: 4 | 5 | ```json 6 | { 7 | "requestId":"$context.requestId", 8 | "ip": "$context.identity.sourceIp", 9 | "apiKey": "$context.identity.apiKey", 10 | "requestTime":"$context.requestTime", 11 | "httpMethod":"$context.httpMethod", 12 | "routeKey":"$context.routeKey", 13 | "path":"$context.path", 14 | "status": $context.status, 15 | "protocol":"$context.protocol", 16 | "integrationStatus": $context.integrationStatus, 17 | "integrationLatency": $context.integrationLatency, 18 | "responseLatency":$context.responseLatency, 19 | "responseLength": $context.responseLength 20 | } 21 | ``` 22 | 23 | You can modify log format to fit your needs (make sure to update code snippet if field names change). 24 | 25 | 26 | See documentation for more details on how to set up API Gateway logging in HTTP (https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-logging.html) and REST (https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-logging.html) APIs. -------------------------------------------------------------------------------- /cloudwatch-insight-apigw-most-popular-paths/snippet.txt: -------------------------------------------------------------------------------- 1 | stats count(*) as requestCount by path 2 | | sort requestCount desc 3 | | limit 10 -------------------------------------------------------------------------------- /cloudwatch-insight-apigw-paths-most-4xx/README.md: -------------------------------------------------------------------------------- 1 | ## Amazon API Gateway Access Logging Setup 2 | 3 | This snippet assumes that Amazon API Gateway logs requests to Amazon CloudWatch Logs using JSON and the following log format: 4 | 5 | ```json 6 | { 7 | "requestId":"$context.requestId", 8 | "ip": "$context.identity.sourceIp", 9 | "apiKey": "$context.identity.apiKey", 10 | "requestTime":"$context.requestTime", 11 | "httpMethod":"$context.httpMethod", 12 | "routeKey":"$context.routeKey", 13 | "path":"$context.path", 14 | "status": $context.status, 15 | "protocol":"$context.protocol", 16 | "integrationStatus": $context.integrationStatus, 17 | "integrationLatency": $context.integrationLatency, 18 | "responseLatency":$context.responseLatency, 19 | "responseLength": $context.responseLength 20 | } 21 | ``` 22 | 23 | You can modify log format to fit your needs (make sure to update code snippet if field names change). 24 | 25 | 26 | See documentation for more details on how to set up API Gateway logging in HTTP (https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-logging.html) and REST (https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-logging.html) APIs. -------------------------------------------------------------------------------- /cloudwatch-insight-apigw-paths-most-4xx/snippet.txt: -------------------------------------------------------------------------------- 1 | stats count(*) as errorCount by status, path, httpMethod 2 | | filter status>=400 and status<=499 3 | | limit 10 -------------------------------------------------------------------------------- /cloudwatch-insight-apigw-paths-most-5xx/README.md: -------------------------------------------------------------------------------- 1 | ## Amazon API Gateway Access Logging Setup 2 | 3 | This snippet assumes that Amazon API Gateway logs requests to Amazon CloudWatch Logs using JSON and the following log format: 4 | 5 | ```json 6 | { 7 | "requestId":"$context.requestId", 8 | "ip": "$context.identity.sourceIp", 9 | "apiKey": "$context.identity.apiKey", 10 | "requestTime":"$context.requestTime", 11 | "httpMethod":"$context.httpMethod", 12 | "routeKey":"$context.routeKey", 13 | "path":"$context.path", 14 | "status": $context.status, 15 | "protocol":"$context.protocol", 16 | "integrationStatus": $context.integrationStatus, 17 | "integrationLatency": $context.integrationLatency, 18 | "responseLatency":$context.responseLatency, 19 | "responseLength": $context.responseLength 20 | } 21 | ``` 22 | 23 | You can modify log format to fit your needs (make sure to update code snippet if field names change). 24 | 25 | 26 | See documentation for more details on how to set up API Gateway logging in HTTP (https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-logging.html) and REST (https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-logging.html) APIs. -------------------------------------------------------------------------------- /cloudwatch-insight-apigw-paths-most-5xx/snippet.txt: -------------------------------------------------------------------------------- 1 | stats count(*) as errorCount by status, path, httpMethod 2 | | filter status>=500 and status<=599 3 | | limit 10 -------------------------------------------------------------------------------- /cloudwatch-insight-apigw-paths-with-most-401-403/README.md: -------------------------------------------------------------------------------- 1 | ## Amazon API Gateway Access Logging Setup 2 | 3 | This snippet assumes that Amazon API Gateway logs requests to Amazon CloudWatch Logs using JSON and the following log format: 4 | 5 | ```json 6 | { 7 | "requestId":"$context.requestId", 8 | "ip": "$context.identity.sourceIp", 9 | "apiKey": "$context.identity.apiKey", 10 | "requestTime":"$context.requestTime", 11 | "httpMethod":"$context.httpMethod", 12 | "routeKey":"$context.routeKey", 13 | "path":"$context.path", 14 | "status": $context.status, 15 | "protocol":"$context.protocol", 16 | "integrationStatus": $context.integrationStatus, 17 | "integrationLatency": $context.integrationLatency, 18 | "responseLatency":$context.responseLatency, 19 | "responseLength": $context.responseLength 20 | } 21 | ``` 22 | 23 | You can modify log format to fit your needs (make sure to update code snippet if field names change). 24 | 25 | 26 | See documentation for more details on how to set up API Gateway logging in HTTP (https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-logging.html) and REST (https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-logging.html) APIs. -------------------------------------------------------------------------------- /cloudwatch-insight-apigw-paths-with-most-401-403/snippet.txt: -------------------------------------------------------------------------------- 1 | stats count(*) as accessDeniedCount by status, path, httpMethod 2 | | filter status=403 or status=401 3 | | limit 10 -------------------------------------------------------------------------------- /cloudwatch-insight-apigw-top-10-api-keys/README.md: -------------------------------------------------------------------------------- 1 | ## Amazon API Gateway Access Logging Setup 2 | 3 | This snippet assumes that Amazon API Gateway logs requests to Amazon CloudWatch Logs using JSON and the following log format: 4 | 5 | ```json 6 | { 7 | "requestId":"$context.requestId", 8 | "ip": "$context.identity.sourceIp", 9 | "apiKey": "$context.identity.apiKey", 10 | "requestTime":"$context.requestTime", 11 | "httpMethod":"$context.httpMethod", 12 | "routeKey":"$context.routeKey", 13 | "path":"$context.path", 14 | "status": $context.status, 15 | "protocol":"$context.protocol", 16 | "integrationStatus": $context.integrationStatus, 17 | "integrationLatency": $context.integrationLatency, 18 | "responseLatency":$context.responseLatency, 19 | "responseLength": $context.responseLength 20 | } 21 | ``` 22 | 23 | You can modify log format to fit your needs (make sure to update code snippet if field names change). 24 | 25 | 26 | See documentation for more details on how to set up API Gateway logging in HTTP (https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-logging.html) and REST (https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-logging.html) APIs. -------------------------------------------------------------------------------- /cloudwatch-insight-apigw-top-10-api-keys/snippet.txt: -------------------------------------------------------------------------------- 1 | stats count(*) as requestCount by apiKey 2 | | sort requestCount desc 3 | | limit 10 -------------------------------------------------------------------------------- /cloudwatch-insight-apigw-top-10-ips/README.md: -------------------------------------------------------------------------------- 1 | ## Amazon API Gateway Access Logging Setup 2 | 3 | This snippet assumes that Amazon API Gateway logs requests to Amazon CloudWatch Logs using JSON and the following log format: 4 | 5 | ```json 6 | { 7 | "requestId":"$context.requestId", 8 | "ip": "$context.identity.sourceIp", 9 | "apiKey": "$context.identity.apiKey", 10 | "requestTime":"$context.requestTime", 11 | "httpMethod":"$context.httpMethod", 12 | "routeKey":"$context.routeKey", 13 | "path":"$context.path", 14 | "status": $context.status, 15 | "protocol":"$context.protocol", 16 | "integrationStatus": $context.integrationStatus, 17 | "integrationLatency": $context.integrationLatency, 18 | "responseLatency":$context.responseLatency, 19 | "responseLength": $context.responseLength 20 | } 21 | ``` 22 | 23 | You can modify log format to fit your needs (make sure to update code snippet if field names change). 24 | 25 | 26 | See documentation for more details on how to set up API Gateway logging in HTTP (https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-logging.html) and REST (https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-logging.html) APIs. -------------------------------------------------------------------------------- /cloudwatch-insight-apigw-top-10-ips/snippet.txt: -------------------------------------------------------------------------------- 1 | stats count(*) as requestCount by ip 2 | | sort requestCount desc 3 | | limit 10 -------------------------------------------------------------------------------- /cloudwatch-insight-cloudtrail-ec2-hosts-that-start-or-stop-in-aws-region/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "EC2 hosts that started or stopped in an AWS Region with AWS CloudTrail", 3 | "description": "Find the Amazon EC2 hosts that were started or stopped in a given AWS Region.", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["cloudtrail"], 6 | "introBox": { 7 | "headline": "How it works", 8 | "text": ["Cloudwatch Log Insight snippet that helps identify EC2 hosts that have started or stopped for a given AWS Region using CloudTrail"] 9 | }, 10 | "gitHub": { 11 | "template": { 12 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-cloudtrail-find-newly-created-users" 13 | } 14 | }, 15 | "snippets": [ 16 | { 17 | "title": "Copy the code into CloudWatch Logs Insights", 18 | "snippetPath": "snippet.txt", 19 | "language": "css" 20 | } 21 | ], 22 | "authors": [ 23 | { 24 | "headline": "Presented by David Boyne", 25 | "name": "David Boyne", 26 | "image": "https://pbs.twimg.com/profile_images/1262283153563140096/DYRDqKg6_400x400.png", 27 | "bio": "Serverless Developer Advocate at AWS", 28 | "linkedin": "", 29 | "twitter": "boyney123" 30 | } 31 | ] 32 | } 33 | -------------------------------------------------------------------------------- /cloudwatch-insight-cloudtrail-ec2-hosts-that-start-or-stop-in-aws-region/snippet.txt: -------------------------------------------------------------------------------- 1 | filter (eventName="StartInstances" or eventName="StopInstances") and awsRegion="us-east-2" -------------------------------------------------------------------------------- /cloudwatch-insight-cloudtrail-find-newly-created-users/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Find information for newly created IAM users using CloudTrail", 3 | "description": "Find the AWS Regions, user names, and ARNs of newly created IAM users.", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["cloudtrail"], 6 | "introBox": { 7 | "headline": "How it works", 8 | "text": ["Cloudwatch Log Insight snippet that helps identify AWS Regions, user names and ARNS of newly created IAM users"] 9 | }, 10 | "gitHub": { 11 | "template": { 12 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-cloudtrail-find-newly-created-users" 13 | } 14 | }, 15 | "snippets": [ 16 | { 17 | "snippetPath": "snippet.txt", 18 | "language": "css" 19 | } 20 | ], 21 | "authors": [ 22 | { 23 | "headline": "Presented by David Boyne", 24 | "name": "David Boyne", 25 | "image": "https://pbs.twimg.com/profile_images/1262283153563140096/DYRDqKg6_400x400.png", 26 | "bio": "Serverless Developer Advocate at AWS", 27 | "linkedin": "", 28 | "twitter": "boyney123" 29 | } 30 | ] 31 | } 32 | -------------------------------------------------------------------------------- /cloudwatch-insight-cloudtrail-find-newly-created-users/snippet.txt: -------------------------------------------------------------------------------- 1 | filter eventName="CreateUser" 2 | | fields awsRegion, requestParameters.userName, responseElements.user.arn -------------------------------------------------------------------------------- /cloudwatch-insight-cloudtrail-number-of-entries-for-service-event-region/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Find the number of log entries with AWS CloudTrail", 3 | "description": "Find the number of log entries for each service, event type, and AWS Region.", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["cloudtrail"], 6 | "introBox": { 7 | "headline": "How it works", 8 | "text": ["Cloudwatch Log Insight snippet that helps identify the number of log entries for each service, event type and AWS Region using CloudTrail"] 9 | }, 10 | "gitHub": { 11 | "template": { 12 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-cloudtrail-number-of-entries-for-service-event-region" 13 | } 14 | }, 15 | "snippets": [ 16 | { 17 | "snippetPath": "snippet.txt", 18 | "language": "css" 19 | } 20 | ], 21 | "authors": [ 22 | { 23 | "headline": "Presented by David Boyne", 24 | "name": "David Boyne", 25 | "image": "https://pbs.twimg.com/profile_images/1262283153563140096/DYRDqKg6_400x400.png", 26 | "bio": "Serverless Developer Advocate at AWS", 27 | "linkedin": "", 28 | "twitter": "boyney123" 29 | } 30 | ] 31 | } 32 | -------------------------------------------------------------------------------- /cloudwatch-insight-cloudtrail-number-of-entries-for-service-event-region/snippet.txt: -------------------------------------------------------------------------------- 1 | stats count(*) by eventSource, eventName, awsRegion -------------------------------------------------------------------------------- /cloudwatch-insight-create-latency-report/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Lambda latency report", 3 | "description": "Create a latency report for your Lambda functions", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["lambda"], 6 | "tags": [ 7 | "Latency" 8 | ], 9 | "introBox": { 10 | "headline": "How it works", 11 | "text": ["Cloudwatch Log Insight snippet that creates a latency report for your Lambda functions."] 12 | }, 13 | "gitHub": { 14 | "template": { 15 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-exception-per-hour" 16 | } 17 | }, 18 | "snippets": [ 19 | { 20 | "snippetPath": "snippet.txt", 21 | "language": "css" 22 | } 23 | ], 24 | "authors": [ 25 | { 26 | "headline": "Presented by David Boyne", 27 | "name": "David Boyne", 28 | "image": "https://pbs.twimg.com/profile_images/1262283153563140096/DYRDqKg6_400x400.png", 29 | "bio": "Serverless Developer Advocate at AWS", 30 | "linkedin": "", 31 | "twitter": "boyney123" 32 | } 33 | ] 34 | } 35 | -------------------------------------------------------------------------------- /cloudwatch-insight-create-latency-report/snippet.txt: -------------------------------------------------------------------------------- 1 | filter @type = "REPORT" | 2 | stats avg(@duration), max(@duration), min(@duration) by bin(5m) -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-by-detail-type-like/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Events that match a pattern for detail-type value", 3 | "description": "Get the EventBridge events that match a pattern for detail-type value", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["eventbridge"], 6 | "tags": [ 7 | "" 8 | ], 9 | "introBox": { 10 | "headline": "How it works", 11 | "text": ["Cloudwatch Log Insight snippet that gets the EventBridge events that matches a pattern for detail-type value"] 12 | }, 13 | "gitHub": { 14 | "template": { 15 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-eventbridge-event-by-detail-type-like" 16 | } 17 | }, 18 | "snippets": [ 19 | { 20 | "snippetPath": "snippet.txt", 21 | "language": "css" 22 | } 23 | ], 24 | "authors": [ 25 | { 26 | "headline": "Presented by Rahul Sringeri", 27 | "name": "Rahul Sringeri", 28 | "image": "", 29 | "bio": "Technical Account Manager at AWS for Strategic Accounts", 30 | "linkedin": "", 31 | "twitter": "" 32 | } 33 | ] 34 | } 35 | -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-by-detail-type-like/snippet.txt: -------------------------------------------------------------------------------- 1 | fields @timestamp 2 | | filter `detail-type` like /sample-value/ # replace sample-value with actual value to be searched 3 | | sort @timestamp desc -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-count-by-source/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-count-by-source/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Events grouped by source", 3 | "description": "Get the number of EventBridge events by source", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["eventbridge"], 6 | "tags": [ 7 | "" 8 | ], 9 | "introBox": { 10 | "headline": "How it works", 11 | "text": ["Cloudwatch Log Insight snippet that counts the number of EventBridge events and groups by source"] 12 | }, 13 | "gitHub": { 14 | "template": { 15 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-eventbridge-event-count-by-source" 16 | } 17 | }, 18 | "snippets": [ 19 | { 20 | "snippetPath": "snippet.txt", 21 | "language": "css" 22 | } 23 | ], 24 | "authors": [ 25 | { 26 | "headline": "Presented by Rahul Sringeri", 27 | "name": "Rahul Sringeri", 28 | "image": "", 29 | "bio": "Technical Account Manager at AWS for Strategic Accounts", 30 | "linkedin": "", 31 | "twitter": "" 32 | } 33 | ] 34 | } 35 | -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-count-by-source/snippet.txt: -------------------------------------------------------------------------------- 1 | fields @timestamp 2 | | stats count(*) as EventsCountBySource by source 3 | | sort @timestamp desc -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-count/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-count/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Events over time grouped by detail-type", 3 | "description": "Get the number of EventBridge events grouped by detail-type", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["eventbridge"], 6 | "tags": [ 7 | "" 8 | ], 9 | "introBox": { 10 | "headline": "How it works", 11 | "text": ["Cloudwatch Log Insight snippet that counts the number of EventBridge events and groups by detail-type"] 12 | }, 13 | "gitHub": { 14 | "template": { 15 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-eventbridge-event-count" 16 | } 17 | }, 18 | "snippets": [ 19 | { 20 | "snippetPath": "snippet.txt", 21 | "language": "css" 22 | } 23 | ], 24 | "authors": [ 25 | { 26 | "headline": "Presented by David Boyne", 27 | "name": "David Boyne", 28 | "image": "https://pbs.twimg.com/profile_images/1262283153563140096/DYRDqKg6_400x400.png", 29 | "bio": "Serverless Developer Advocate at AWS", 30 | "linkedin": "", 31 | "twitter": "boyney123" 32 | } 33 | ] 34 | } 35 | -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-count/snippet.txt: -------------------------------------------------------------------------------- 1 | fields @timestamp, @message 2 | | stats count(*) as numberOfEvents by `detail-type` 3 | | sort numberOfEvents desc -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-detail-field-within-a-numeric-range/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-detail-field-within-a-numeric-range/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Events with detail field value falling in a given numeric range ", 3 | "description": "Get the EventBridge events for a given detail field that has values within a given numeric range", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["eventbridge"], 6 | "tags": [ 7 | "" 8 | ], 9 | "introBox": { 10 | "headline": "How it works", 11 | "text": ["Cloudwatch Log Insight snippet that returns the EventBridge events for a given detail field that has values within a given numeric range"] 12 | }, 13 | "gitHub": { 14 | "template": { 15 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-eventbridge-event-detail-field-within-a-numeric-range" 16 | } 17 | }, 18 | "snippets": [ 19 | { 20 | "snippetPath": "snippet.txt", 21 | "language": "css" 22 | } 23 | ], 24 | "authors": [ 25 | { 26 | "headline": "Presented by Rahul Sringeri", 27 | "name": "Rahul Sringeri", 28 | "image": "", 29 | "bio": "Technical Account Manager at AWS for Strategic Accounts", 30 | "linkedin": "", 31 | "twitter": "" 32 | } 33 | ] 34 | } -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-detail-field-within-a-numeric-range/snippet.txt: -------------------------------------------------------------------------------- 1 | fields @timestamp 2 | | filter detail.field-value >= N1 and detail.field-value <= N2 # replace field-value, N1, N2 with actual values. N1 and N2 are the numeric range. 3 | | sort @timestamp desc -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-filter-by-detail-field-equal-to/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-filter-by-detail-field-equal-to/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Filter Events by value of a detail field", 3 | "description": "Get the EventBridge events by filtering on a detail field", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["eventbridge"], 6 | "tags": [ 7 | "" 8 | ], 9 | "introBox": { 10 | "headline": "How it works", 11 | "text": ["Cloudwatch Log Insight snippet that filters the EventBridge events by value of a detail field"] 12 | }, 13 | "gitHub": { 14 | "template": { 15 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-eventbridge-event-filter-by-detail-field" 16 | } 17 | }, 18 | "snippets": [ 19 | { 20 | "snippetPath": "snippet.txt", 21 | "language": "css" 22 | } 23 | ], 24 | "authors": [ 25 | { 26 | "headline": "Presented by Rahul Sringeri", 27 | "name": "Rahul Sringeri", 28 | "image": "", 29 | "bio": "Technical Account Manager at AWS for Strategic Accounts", 30 | "linkedin": "", 31 | "twitter": "" 32 | } 33 | ] 34 | } 35 | -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-filter-by-detail-field-equal-to/snippet.txt: -------------------------------------------------------------------------------- 1 | fields @timestamp 2 | | filter detail.field-name = "field-value" # replace field-name and field-value with actual values 3 | | sort @timestamp desc -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-filter-by-detail-field-not-equal-to/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-filter-by-detail-field-not-equal-to/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Filter Events by detail field value not equal to a given value", 3 | "description": "Get the EventBridge events by filtering on a detail field value that is not equal to a given value ", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["eventbridge"], 6 | "tags": [ 7 | "" 8 | ], 9 | "introBox": { 10 | "headline": "How it works", 11 | "text": ["Cloudwatch Log Insight snippet that filters the EventBridge events on a detail field value not equal to a given value"] 12 | }, 13 | "gitHub": { 14 | "template": { 15 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-eventbridge-event-filter-by-detail-field-not-equal-to" 16 | } 17 | }, 18 | "snippets": [ 19 | { 20 | "snippetPath": "snippet.txt", 21 | "language": "css" 22 | } 23 | ], 24 | "authors": [ 25 | { 26 | "headline": "Presented by Rahul Sringeri", 27 | "name": "Rahul Sringeri", 28 | "image": "", 29 | "bio": "Technical Account Manager at AWS for Strategic Accounts", 30 | "linkedin": "", 31 | "twitter": "" 32 | } 33 | ] 34 | } -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-filter-by-detail-field-not-equal-to/snippet.txt: -------------------------------------------------------------------------------- 1 | fields @timestamp 2 | | filter detail.field-name != "field-value" # replace field-name and field-value with actual values 3 | | sort @timestamp desc -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-filter-by-detail-type-equal-to/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-filter-by-detail-type-equal-to/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Events that match the value of detail-type", 3 | "description": "Get the EventBridge events that match the value of detail-type", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["eventbridge"], 6 | "tags": [ 7 | "" 8 | ], 9 | "introBox": { 10 | "headline": "How it works", 11 | "text": ["Cloudwatch Log Insight snippet that filters the EventBridge events by value of detail-type"] 12 | }, 13 | "gitHub": { 14 | "template": { 15 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-eventbridge-event-filter-by-detail-type" 16 | } 17 | }, 18 | "snippets": [ 19 | { 20 | "snippetPath": "snippet.txt", 21 | "language": "css" 22 | } 23 | ], 24 | "authors": [ 25 | { 26 | "headline": "Presented by Rahul Sringeri", 27 | "name": "Rahul Sringeri", 28 | "image": "", 29 | "bio": "Technical Account Manager at AWS for Strategic Accounts", 30 | "linkedin": "", 31 | "twitter": "" 32 | } 33 | ] 34 | } 35 | -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-filter-by-detail-type-equal-to/snippet.txt: -------------------------------------------------------------------------------- 1 | fields @timestamp 2 | | filter `detail-type` = "detail-type-value" # replace detail-type-value with the actual value 3 | | sort @timestamp desc -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-filter-detail-field-with-values-in-array/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-filter-detail-field-with-values-in-array/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Events that match a value in detail-field that has an array of values", 3 | "description": "Get the EventBridge events that match a value in detail-field that has an array of values", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["eventbridge"], 6 | "tags": [ 7 | "" 8 | ], 9 | "introBox": { 10 | "headline": "How it works", 11 | "text": ["Cloudwatch Log Insight snippet that gets the EventBridge events that matches a value in detail-field that has an array of values"] 12 | }, 13 | "gitHub": { 14 | "template": { 15 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-eventbridge-event-filter-detail-field-with-values-in-array" 16 | } 17 | }, 18 | "snippets": [ 19 | { 20 | "snippetPath": "snippet.txt", 21 | "language": "css" 22 | } 23 | ], 24 | "authors": [ 25 | { 26 | "headline": "Presented by Rahul Sringeri", 27 | "name": "Rahul Sringeri", 28 | "image": "", 29 | "bio": "Technical Account Manager at AWS for Strategic Accounts", 30 | "linkedin": "", 31 | "twitter": "" 32 | } 33 | ] 34 | } 35 | -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-filter-detail-field-with-values-in-array/snippet.txt: -------------------------------------------------------------------------------- 1 | fields @timestamp 2 | | filter detail.array-field.n1 = "sample-value" # replace array-field with the field name having values as array, n1 with array position and sample-value with value to filter. 3 | | sort @timestamp desc -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-find-if-detail-field-exists/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-find-if-detail-field-exists/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Get Events if a given detail field is present ", 3 | "description": "Get the EventBridge events if detail field is present", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["eventbridge"], 6 | "tags": [ 7 | "" 8 | ], 9 | "introBox": { 10 | "headline": "How it works", 11 | "text": ["Cloudwatch Log Insight snippet that returns the EventBridge events if a given detail field is present"] 12 | }, 13 | "gitHub": { 14 | "template": { 15 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-eventbridge-event-find-if-detail-field-exists" 16 | } 17 | }, 18 | "snippets": [ 19 | { 20 | "snippetPath": "snippet.txt", 21 | "language": "css" 22 | } 23 | ], 24 | "authors": [ 25 | { 26 | "headline": "Presented by Rahul Sringeri", 27 | "name": "Rahul Sringeri", 28 | "image": "", 29 | "bio": "Technical Account Manager at AWS for Strategic Accounts", 30 | "linkedin": "", 31 | "twitter": "" 32 | } 33 | ] 34 | } 35 | -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-find-if-detail-field-exists/snippet.txt: -------------------------------------------------------------------------------- 1 | fields @timestamp 2 | | filter ispresent(detail.field-name) # replace field-name with the actual value 3 | | sort @timestamp desc -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-per-hour/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-per-hour/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Events per hour ", 3 | "description": "Get the EventBridge events per hour", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["eventbridge"], 6 | "tags": [ 7 | "" 8 | ], 9 | "introBox": { 10 | "headline": "How it works", 11 | "text": ["Cloudwatch Log Insight snippet that returns the EventBridge events per hour"] 12 | }, 13 | "gitHub": { 14 | "template": { 15 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-eventbridge-event-per-minute" 16 | } 17 | }, 18 | "snippets": [ 19 | { 20 | "snippetPath": "snippet.txt", 21 | "language": "css" 22 | } 23 | ], 24 | "authors": [ 25 | { 26 | "headline": "Presented by Rahul Sringeri", 27 | "name": "Rahul Sringeri", 28 | "image": "", 29 | "bio": "Technical Account Manager at AWS for Strategic Accounts", 30 | "linkedin": "", 31 | "twitter": "" 32 | } 33 | ] 34 | } -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-per-hour/snippet.txt: -------------------------------------------------------------------------------- 1 | fields @timestamp 2 | | filter ispresent(`detail-type`) 3 | | stats count(*) as CountOfEventsPerHour by bin(1h) 4 | | sort @timestamp desc -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-per-minute/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-per-minute/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Events per minute ", 3 | "description": "Get the EventBridge events per minute", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["eventbridge"], 6 | "tags": [ 7 | "" 8 | ], 9 | "introBox": { 10 | "headline": "How it works", 11 | "text": ["Cloudwatch Log Insight snippet that returns the EventBridge events per minute"] 12 | }, 13 | "gitHub": { 14 | "template": { 15 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-eventbridge-event-per-minute" 16 | } 17 | }, 18 | "snippets": [ 19 | { 20 | "snippetPath": "snippet.txt", 21 | "language": "css" 22 | } 23 | ], 24 | "authors": [ 25 | { 26 | "headline": "Presented by Rahul Sringeri", 27 | "name": "Rahul Sringeri", 28 | "image": "", 29 | "bio": "Technical Account Manager at AWS for Strategic Accounts", 30 | "linkedin": "", 31 | "twitter": "" 32 | } 33 | ] 34 | } -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-per-minute/snippet.txt: -------------------------------------------------------------------------------- 1 | fields @timestamp 2 | | filter ispresent(`detail-type`) 3 | | stats count(*) as CountOfEventsPerMinute by bin(1m) 4 | | sort @timestamp desc -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-where-detail-field-value-in/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-where-detail-field-value-in/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Events with detail field that matches any value in a list ", 3 | "description": "Get the EventBridge events with a specific detail field that matches any value in a list.", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["eventbridge"], 6 | "tags": [ 7 | "" 8 | ], 9 | "introBox": { 10 | "headline": "How it works", 11 | "text": ["Cloudwatch Log Insight snippet that returns the EventBridge events for a given detail field that that matches any value in a list"] 12 | }, 13 | "gitHub": { 14 | "template": { 15 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-eventbridge-event-where-detail-field-value-in" 16 | } 17 | }, 18 | "snippets": [ 19 | { 20 | "snippetPath": "snippet.txt", 21 | "language": "css" 22 | } 23 | ], 24 | "authors": [ 25 | { 26 | "headline": "Presented by Rahul Sringeri", 27 | "name": "Rahul Sringeri", 28 | "image": "", 29 | "bio": "Technical Account Manager at AWS for Strategic Accounts", 30 | "linkedin": "", 31 | "twitter": "" 32 | } 33 | ] 34 | } -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-where-detail-field-value-in/snippet.txt: -------------------------------------------------------------------------------- 1 | fields @timestamp 2 | | filter detail.field-value IN ["value1", "value2", "value3"] # replace field-value and value1, value2, value3 with actual values. 3 | | sort @timestamp desc -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-where-detail-field-value-not-in/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-where-detail-field-value-not-in/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Events with detail field that does not match any value in a list ", 3 | "description": "Get the EventBridge events with a specific detail field that does not match any value in a list.", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["eventbridge"], 6 | "tags": [ 7 | "" 8 | ], 9 | "introBox": { 10 | "headline": "How it works", 11 | "text": ["Cloudwatch Log Insight snippet that returns the EventBridge events for a given detail field that that does not matches any value in a list"] 12 | }, 13 | "gitHub": { 14 | "template": { 15 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-eventbridge-event-where-detail-field-value-not-in" 16 | } 17 | }, 18 | "snippets": [ 19 | { 20 | "snippetPath": "snippet.txt", 21 | "language": "css" 22 | } 23 | ], 24 | "authors": [ 25 | { 26 | "headline": "Presented by Rahul Sringeri", 27 | "name": "Rahul Sringeri", 28 | "image": "", 29 | "bio": "Technical Account Manager at AWS for Strategic Accounts", 30 | "linkedin": "", 31 | "twitter": "" 32 | } 33 | ] 34 | } -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-where-detail-field-value-not-in/snippet.txt: -------------------------------------------------------------------------------- 1 | fields @timestamp 2 | | filter detail.field-value NOT IN ["value1", "value2", "value3"] # replace field-value and value1, value2, value3 with actual values. 3 | | sort @timestamp desc -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-where-value-equals-nested-detail-field-value/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-where-value-equals-nested-detail-field-value/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Events that match a value in detail-nested-field", 3 | "description": "Get the EventBridge events that match a value in detail-nested-field", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["eventbridge"], 6 | "tags": [ 7 | "" 8 | ], 9 | "introBox": { 10 | "headline": "How it works", 11 | "text": ["Cloudwatch Log Insight snippet that gets the EventBridge events that matches a value in detail-nested-field"] 12 | }, 13 | "gitHub": { 14 | "template": { 15 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-eventbridge-event-where-value-equals-nested-detail-field-value" 16 | } 17 | }, 18 | "snippets": [ 19 | { 20 | "snippetPath": "snippet.txt", 21 | "language": "css" 22 | } 23 | ], 24 | "authors": [ 25 | { 26 | "headline": "Presented by Rahul Sringeri", 27 | "name": "Rahul Sringeri", 28 | "image": "", 29 | "bio": "Technical Account Manager at AWS for Strategic Accounts", 30 | "linkedin": "", 31 | "twitter": "" 32 | } 33 | ] 34 | } 35 | -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-where-value-equals-nested-detail-field-value/snippet.txt: -------------------------------------------------------------------------------- 1 | fields @timestamp 2 | | filter detail.field1.field2 = "sample-value" # replace field1, field2, sample-value with appropriate values. 3 | | sort @timestamp desc -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-with-detail-field-empty/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-with-detail-field-empty/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Events which have no value for a given detail field ", 3 | "description": "Get the EventBridge events for a given detail field that has no value", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["eventbridge"], 6 | "tags": [ 7 | "" 8 | ], 9 | "introBox": { 10 | "headline": "How it works", 11 | "text": ["Cloudwatch Log Insight snippet that returns the EventBridge events for a given detail field that has no value"] 12 | }, 13 | "gitHub": { 14 | "template": { 15 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-eventbridge-event-with-detail-field-empty" 16 | } 17 | }, 18 | "snippets": [ 19 | { 20 | "snippetPath": "snippet.txt", 21 | "language": "css" 22 | } 23 | ], 24 | "authors": [ 25 | { 26 | "headline": "Presented by Rahul Sringeri", 27 | "name": "Rahul Sringeri", 28 | "image": "", 29 | "bio": "Technical Account Manager at AWS for Strategic Accounts", 30 | "linkedin": "", 31 | "twitter": "" 32 | } 33 | ] 34 | } -------------------------------------------------------------------------------- /cloudwatch-insight-eventbridge-event-with-detail-field-empty/snippet.txt: -------------------------------------------------------------------------------- 1 | fields @timestamp 2 | | filter isempty(detail.field-value) # replace field-value with the actual value 3 | | sort @timestamp desc -------------------------------------------------------------------------------- /cloudwatch-insight-exception-per-hour/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-exception-per-hour/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Number of exceptions per hour", 3 | "description": "Find and list the number of exceptions per hour", 4 | "type": "CloudWatch Logs Insights", 5 | "services": [], 6 | "tags": [ 7 | "Handling Errors" 8 | ], 9 | "introBox": { 10 | "headline": "How it works", 11 | "text": ["Cloudwatch Log Insight snippet that helps you find the number of exceptions per hour for selected log groups."] 12 | }, 13 | "gitHub": { 14 | "template": { 15 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-exception-per-hour" 16 | } 17 | }, 18 | "snippets": [ 19 | { 20 | "snippetPath": "snippet.txt", 21 | "language": "css" 22 | } 23 | ], 24 | "authors": [ 25 | { 26 | "headline": "Presented by David Boyne", 27 | "name": "David Boyne", 28 | "image": "https://pbs.twimg.com/profile_images/1262283153563140096/DYRDqKg6_400x400.png", 29 | "bio": "Serverless Developer Advocate at AWS", 30 | "linkedin": "", 31 | "twitter": "boyney123" 32 | } 33 | ] 34 | } 35 | -------------------------------------------------------------------------------- /cloudwatch-insight-exception-per-hour/snippet.txt: -------------------------------------------------------------------------------- 1 | filter @message like /Exception/ 2 | | stats count(*) as exceptionCount by bin(1h) 3 | | sort exceptionCount desc -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-100-highest-billed-invocations/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-100-highest-billed-invocations/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Top 100 highest billed invocations", 3 | "description": "Returns the top 100 highest billed invocations.", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["lambda"], 6 | "introBox": { 7 | "headline": "How it works", 8 | "text": ["Cloudwatch Log Insight snippet that returns the top highest billed Lambda invocations"] 9 | }, 10 | "gitHub": { 11 | "template": { 12 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-lambda-100-highest-billed-invocations" 13 | } 14 | }, 15 | "snippets": [ 16 | { 17 | "snippetPath": "snippet.txt", 18 | "language": "css" 19 | } 20 | ], 21 | "authors": [ 22 | { 23 | "headline": "Presented by David Boyne", 24 | "name": "David Boyne", 25 | "image": "https://pbs.twimg.com/profile_images/1262283153563140096/DYRDqKg6_400x400.png", 26 | "bio": "Serverless Developer Advocate at AWS", 27 | "linkedin": "", 28 | "twitter": "boyney123" 29 | } 30 | ] 31 | } 32 | -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-100-highest-billed-invocations/snippet.txt: -------------------------------------------------------------------------------- 1 | filter @type = "REPORT" 2 | | fields @requestId, @billedDuration 3 | | sort by @billedDuration desc 4 | | limit 100 -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-average-memory-across-invocations/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-average-memory-across-invocations/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Average memory used across Lambda invocations", 3 | "description": "Returns the average memory that has been used across Lambda invocations .", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["lambda"], 6 | "introBox": { 7 | "headline": "How it works", 8 | "text": ["Cloudwatch Log Insight snippet that helps you understand the average memory for Lambda invocations."] 9 | }, 10 | "gitHub": { 11 | "template": { 12 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-lambda-average-memory-across-invocations" 13 | } 14 | }, 15 | "snippets": [ 16 | { 17 | "snippetPath": "snippet.txt", 18 | "language": "css" 19 | } 20 | ], 21 | "authors": [ 22 | { 23 | "headline": "Presented by David Boyne", 24 | "name": "David Boyne", 25 | "image": "https://pbs.twimg.com/profile_images/1262283153563140096/DYRDqKg6_400x400.png", 26 | "bio": "Serverless Developer Advocate at AWS", 27 | "linkedin": "", 28 | "twitter": "boyney123" 29 | } 30 | ] 31 | } 32 | -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-average-memory-across-invocations/snippet.txt: -------------------------------------------------------------------------------- 1 | avgMemoryUsedPERC, 2 | avg(@billedDuration) as avgDurationMS 3 | by bin(5m) -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-cold-start-invocations-byfunction/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-cold-start-invocations-byfunction/snippet.txt: -------------------------------------------------------------------------------- 1 | filter @type = "REPORT" 2 | | stats sum(ispresent(@initDuration))/count() * 100 as 3 | coldStartPct, avg(@duration) 4 | by bin(5m) -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-cold-start-invocations/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-cold-start-invocations/snippet.txt: -------------------------------------------------------------------------------- 1 | filter @type = "REPORT" 2 | | stats sum(ispresent(@initDuration))/count() * 100 as 3 | coldStartPct, avg(@duration) 4 | by bin(5m) -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-cold-starts-count-and-duration/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-cold-starts-count-and-duration/snippet.txt: -------------------------------------------------------------------------------- 1 | filter @type="REPORT" and ispresent(@initDuration) 2 | | stats count() as coldStarts, avg(@initDuration), min(@initDuration), max(@initDuration) by bin(5m) -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-invocation-where-lambda-exited/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-invocation-where-lambda-exited/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Invocations where Lambda exited", 3 | "description": "Returns the number of invocations where Lambda exited", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["lambda"], 6 | "introBox": { 7 | "headline": "How it works", 8 | "text": ["Cloudwatch Log Insight snippet that returns the number of invocations where Lambda exited"] 9 | }, 10 | "gitHub": { 11 | "template": { 12 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-lambda-invocation-where-lambda-exited" 13 | } 14 | }, 15 | "snippets": [ 16 | { 17 | "snippetPath": "snippet.txt", 18 | "language": "css" 19 | } 20 | ], 21 | "authors": [ 22 | { 23 | "headline": "Presented by David Boyne", 24 | "name": "David Boyne", 25 | "image": "https://pbs.twimg.com/profile_images/1262283153563140096/DYRDqKg6_400x400.png", 26 | "bio": "Serverless Developer Advocate at AWS", 27 | "linkedin": "", 28 | "twitter": "boyney123" 29 | } 30 | ] 31 | } 32 | -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-invocation-where-lambda-exited/snippet.txt: -------------------------------------------------------------------------------- 1 | filter @message like /Process exited/ 2 | | stats count() by bin(30m) -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-invocations-timed-out/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-invocations-timed-out/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Invocations where Lambda timed out", 3 | "description": "Returns the number of invocations where Lambda timed out", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["lambda"], 6 | "introBox": { 7 | "headline": "How it works", 8 | "text": ["Cloudwatch Log Insight snippet that returns the number of invocations where Lambda timed out"] 9 | }, 10 | "gitHub": { 11 | "template": { 12 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-lambda-invocations-timed-out" 13 | } 14 | }, 15 | "snippets": [ 16 | { 17 | "snippetPath": "snippet.txt", 18 | "language": "css" 19 | } 20 | ], 21 | "authors": [ 22 | { 23 | "headline": "Presented by David Boyne", 24 | "name": "David Boyne", 25 | "image": "https://pbs.twimg.com/profile_images/1262283153563140096/DYRDqKg6_400x400.png", 26 | "bio": "Serverless Developer Advocate at AWS", 27 | "linkedin": "", 28 | "twitter": "boyney123" 29 | } 30 | ] 31 | } 32 | -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-invocations-timed-out/snippet.txt: -------------------------------------------------------------------------------- 1 | filter @message like /Task timed out/ 2 | | stats count() by bin(30m) -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-last-100-errors/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-last-100-errors/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Last 100 errors", 3 | "description": "Returns the last 100 errors in your Lambda log group.", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["lambda"], 6 | "introBox": { 7 | "headline": "How it works", 8 | "text": ["Cloudwatch Log Insight snippet that returns the last 100 errors for your Lambda log group"] 9 | }, 10 | "gitHub": { 11 | "template": { 12 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-lambda-last-100-errors" 13 | } 14 | }, 15 | "snippets": [ 16 | { 17 | "snippetPath": "snippet.txt", 18 | "language": "css" 19 | } 20 | ], 21 | "authors": [ 22 | { 23 | "headline": "Presented by David Boyne", 24 | "name": "David Boyne", 25 | "image": "https://pbs.twimg.com/profile_images/1262283153563140096/DYRDqKg6_400x400.png", 26 | "bio": "Serverless Developer Advocate at AWS", 27 | "linkedin": "", 28 | "twitter": "boyney123" 29 | } 30 | ] 31 | } 32 | -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-last-100-errors/snippet.txt: -------------------------------------------------------------------------------- 1 | fields Timestamp, LogLevel, Message 2 | | filter LogLevel == "ERR" 3 | | sort @timestamp desc 4 | | limit 100 -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-max-assigned-memory/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-max-assigned-memory/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Lambda invocations using 100% of assigned memory", 3 | "description": "Returns the number of Lambda invocations that used 100% of assigned memory.", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["lambda"], 6 | "introBox": { 7 | "headline": "How it works", 8 | "text": ["Cloudwatch Log Insight snippet that helps you identify any Lambda invocations that have used 100% memory"] 9 | }, 10 | "gitHub": { 11 | "template": { 12 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-lambda-max-assigned-memory" 13 | } 14 | }, 15 | "snippets": [ 16 | { 17 | "snippetPath": "snippet.txt", 18 | "language": "css" 19 | } 20 | ], 21 | "authors": [ 22 | { 23 | "headline": "Presented by David Boyne", 24 | "name": "David Boyne", 25 | "image": "https://pbs.twimg.com/profile_images/1262283153563140096/DYRDqKg6_400x400.png", 26 | "bio": "Serverless Developer Advocate at AWS", 27 | "linkedin": "", 28 | "twitter": "boyney123" 29 | } 30 | ] 31 | } 32 | -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-max-assigned-memory/snippet.txt: -------------------------------------------------------------------------------- 1 | filter @type = "REPORT" and @maxMemoryUsed=@memorySize 2 | | stats 3 | count_distinct(@requestId) 4 | by bin(30m) -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-memory-debugger/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-memory-debugger/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Lambda memory report to tell you if you over provisioned", 3 | "description": "Returns a report that looks at innvocations as calculates if you are using the correct amount of memory or not", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["lambda"], 6 | "introBox": { 7 | "headline": "How it works", 8 | "text": ["Cloudwatch Log Insight snippet that returns a report that shows you the smallest, average and max memory used across innvocations, as well as the amount of memory over provisioned"] 9 | }, 10 | "gitHub": { 11 | "template": { 12 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-lambda-memory-debugger" 13 | } 14 | }, 15 | "snippets": [ 16 | { 17 | "snippetPath": "snippet.txt", 18 | "language": "css" 19 | } 20 | ], 21 | "authors": [ 22 | { 23 | "headline": "Presented by David Boyne", 24 | "name": "David Boyne", 25 | "image": "https://pbs.twimg.com/profile_images/1262283153563140096/DYRDqKg6_400x400.png", 26 | "bio": "Serverless Developer Advocate at AWS", 27 | "linkedin": "", 28 | "twitter": "boyney123" 29 | } 30 | ] 31 | } 32 | -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-memory-debugger/snippet.txt: -------------------------------------------------------------------------------- 1 | filter @type = "REPORT" 2 | | stats max(@memorySize / 1000 / 1000) as provisonedMemoryMB, 3 | min(@maxMemoryUsed / 1000 / 1024) as smallestMemoryRequestMB, 4 | avg(@maxMemoryUsed / 1024 / 1024) as avgMemoryUsedMB, 5 | max(@maxMemoryUsed / 1024 / 1024) as maxMemoryUsedMB, 6 | provisonedMemoryMB - maxMemoryUsedMB as overProvisionedMB -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-percentile-duration-report/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-percentile-duration-report/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Percentile report of Lambda duration", 3 | "description": "Returns report of the 99th, 95th and 905 percentile for Lambda log group. .", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["lambda"], 6 | "introBox": { 7 | "headline": "How it works", 8 | "text": ["Cloudwatch Log Insight snippet that returns a percentile report for duration"] 9 | }, 10 | "gitHub": { 11 | "template": { 12 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-lambda-percentile-duration-report" 13 | } 14 | }, 15 | "snippets": [ 16 | { 17 | "snippetPath": "snippet.txt", 18 | "language": "css" 19 | } 20 | ], 21 | "authors": [ 22 | { 23 | "headline": "Presented by David Boyne", 24 | "name": "David Boyne", 25 | "image": "https://pbs.twimg.com/profile_images/1262283153563140096/DYRDqKg6_400x400.png", 26 | "bio": "Serverless Developer Advocate at AWS", 27 | "linkedin": "", 28 | "twitter": "boyney123" 29 | } 30 | ] 31 | } 32 | -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-percentile-duration-report/snippet.txt: -------------------------------------------------------------------------------- 1 | filter @type = "REPORT" 2 | | stats 3 | avg(@billedDuration) as Average, 4 | percentile(@billedDuration, 99) as NinetyNinth, 5 | percentile(@billedDuration, 95) as NinetyFifth, 6 | percentile(@billedDuration, 90) as Ninetieth 7 | by bin(30m) -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-percentile-memory-report/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-percentile-memory-report/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Percentile report of Lambda memory usage", 3 | "description": "Returns percentile report of Lambda memory usage", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["lambda"], 6 | "introBox": { 7 | "headline": "How it works", 8 | "text": ["Cloudwatch Log Insight snippet that returns a percentile report for memory usage"] 9 | }, 10 | "gitHub": { 11 | "template": { 12 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-lambda-percentile-memory-report" 13 | } 14 | }, 15 | "snippets": [ 16 | { 17 | "snippetPath": "snippet.txt", 18 | "language": "css" 19 | } 20 | ], 21 | "authors": [ 22 | { 23 | "headline": "Presented by David Boyne", 24 | "name": "David Boyne", 25 | "image": "https://pbs.twimg.com/profile_images/1262283153563140096/DYRDqKg6_400x400.png", 26 | "bio": "Serverless Developer Advocate at AWS", 27 | "linkedin": "", 28 | "twitter": "boyney123" 29 | } 30 | ] 31 | } 32 | -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-percentile-memory-report/snippet.txt: -------------------------------------------------------------------------------- 1 | filter @type="REPORT" 2 | | stats avg(@maxMemoryUsed/1024/1024) as mean_MemoryUsed, 3 | min(@maxMemoryUsed/1024/1024) as min_MemoryUsed, 4 | max(@maxMemoryUsed/1024/1024) as max_MemoryUsed, 5 | percentile(@maxMemoryUsed/1024/1024, 95) as Percentile95 -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-total-innvocations-vs-coldstarts/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-total-innvocations-vs-coldstarts/snippet.txt: -------------------------------------------------------------------------------- 1 | filter @type = "REPORT" | 2 | stats count() as TotalInvocations, count(@initDuration) as TotalColdStarts -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-visualization-of-memory-statisitcs/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-visualization-of-memory-statisitcs/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Visualization of memory statistics for Lambda", 3 | "description": "Returns a report showing the max, avg and min memory usage..", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["lambda"], 6 | "introBox": { 7 | "headline": "How it works", 8 | "text": ["Cloudwatch Log Insight snippet that shows a report of memory statistics for your Lambda log"] 9 | }, 10 | "gitHub": { 11 | "template": { 12 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-lambda-visualization-of-memory-statisitcs" 13 | } 14 | }, 15 | "snippets": [ 16 | { 17 | "snippetPath": "snippet.txt", 18 | "language": "css" 19 | } 20 | ], 21 | "authors": [ 22 | { 23 | "headline": "Presented by David Boyne", 24 | "name": "David Boyne", 25 | "image": "https://pbs.twimg.com/profile_images/1262283153563140096/DYRDqKg6_400x400.png", 26 | "bio": "Serverless Developer Advocate at AWS", 27 | "linkedin": "", 28 | "twitter": "boyney123" 29 | } 30 | ] 31 | } 32 | -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-visualization-of-memory-statisitcs/snippet.txt: -------------------------------------------------------------------------------- 1 | filter @type = "REPORT" 2 | | stats 3 | max(@maxMemoryUsed / 1024 / 1024) as maxMemMB, 4 | avg(@maxMemoryUsed / 1024 / 1024) as avgMemMB, 5 | min(@maxMemoryUsed / 1024 / 1024) as minMemMB, 6 | (avg(@maxMemoryUsed / 1024 / 1024) / max(@memorySize / 1024 / 1024)) * 100 as avgMemUsedPct, 7 | avg(@billedDuration) as avgDurationMS 8 | by bin(30m) -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-warm-starts/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-lambda-warm-starts/snippet.txt: -------------------------------------------------------------------------------- 1 | filter @type = "REPORT" and @message not like /(?i)(Init Duration)/ 2 | | stats 3 | avg(@duration) as Average, 4 | pct(@duration, 99) as NinetyNinth, 5 | pct(@duration, 95) as NinetyFifth, 6 | pct(@duration, 90) as Ninetieth 7 | by bin(1m) 8 | -------------------------------------------------------------------------------- /cloudwatch-insight-overprovisioned-memory-for-lambda/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-overprovisioned-memory-for-lambda/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Determine the amount of overprovisioned memory.", 3 | "description": "Show the amount of overprovisioned memory for Lambda", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["lambda"], 6 | "tags": [ 7 | "Memory" 8 | ], 9 | "introBox": { 10 | "headline": "How it works", 11 | "text": ["Cloudwatch Log Insight snippet that shows overprovisioned memory for Lambda"] 12 | }, 13 | "gitHub": { 14 | "template": { 15 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-overprovisioned-memory-for-lambda" 16 | } 17 | }, 18 | "snippets": [ 19 | { 20 | "snippetPath": "snippet.txt", 21 | "language": "css" 22 | } 23 | ], 24 | "authors": [ 25 | { 26 | "headline": "Presented by David Boyne", 27 | "name": "David Boyne", 28 | "image": "https://pbs.twimg.com/profile_images/1262283153563140096/DYRDqKg6_400x400.png", 29 | "bio": "Serverless Developer Advocate at AWS", 30 | "linkedin": "", 31 | "twitter": "boyney123" 32 | } 33 | ] 34 | } 35 | -------------------------------------------------------------------------------- /cloudwatch-insight-overprovisioned-memory-for-lambda/snippet.txt: -------------------------------------------------------------------------------- 1 | filter @type = "REPORT" 2 | | stats max(@memorySize / 1000 / 1000) as provisonedMemoryMB, 3 | min(@maxMemoryUsed / 1000 / 1000) as smallestMemoryRequestMB, 4 | avg(@maxMemoryUsed / 1000 / 1000) as avgMemoryUsedMB, 5 | max(@maxMemoryUsed / 1000 / 1000) as maxMemoryUsedMB, 6 | provisonedMemoryMB - maxMemoryUsedMB as overProvisionedMB -------------------------------------------------------------------------------- /cloudwatch-insight-recently-added-logs/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-recently-added-logs/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "25 most recent added logs events", 3 | "description": "Find the 25 most recent added log events.", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["lambda"], 6 | "introBox": { 7 | "headline": "How it works", 8 | "text": ["Cloudwatch Log Insight snippet that helps you find the last 25 added log events."] 9 | }, 10 | "gitHub": { 11 | "template": { 12 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-exception-per-hour" 13 | } 14 | }, 15 | "snippets": [ 16 | { 17 | "snippetPath": "snippet.txt", 18 | "language": "css" 19 | } 20 | ], 21 | "authors": [ 22 | { 23 | "headline": "Presented by David Boyne", 24 | "name": "David Boyne", 25 | "image": "https://pbs.twimg.com/profile_images/1262283153563140096/DYRDqKg6_400x400.png", 26 | "bio": "Serverless Developer Advocate at AWS", 27 | "linkedin": "", 28 | "twitter": "boyney123" 29 | } 30 | ] 31 | } 32 | -------------------------------------------------------------------------------- /cloudwatch-insight-recently-added-logs/snippet.txt: -------------------------------------------------------------------------------- 1 | fields @timestamp, @message | sort @timestamp desc | limit 25 -------------------------------------------------------------------------------- /cloudwatch-insight-route53-distribution-of-records-per-hours/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-route53-distribution-of-records-per-hours/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Distribution of records per hour for Route 53", 3 | "description": "Find the distribution of records per hour by query type.", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["route53"], 6 | "introBox": { 7 | "headline": "How it works", 8 | "text": ["Cloudwatch Log Insight snippet that helps you find distribution of records for Route 53"] 9 | }, 10 | "gitHub": { 11 | "template": { 12 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-route53-distribution-of-records-per-hours" 13 | } 14 | }, 15 | "snippets": [ 16 | { 17 | "snippetPath": "snippet.txt", 18 | "language": "css" 19 | } 20 | ], 21 | "authors": [ 22 | { 23 | "headline": "Presented by David Boyne", 24 | "name": "David Boyne", 25 | "image": "https://pbs.twimg.com/profile_images/1262283153563140096/DYRDqKg6_400x400.png", 26 | "bio": "Serverless Developer Advocate at AWS", 27 | "linkedin": "", 28 | "twitter": "boyney123" 29 | } 30 | ] 31 | } 32 | -------------------------------------------------------------------------------- /cloudwatch-insight-route53-distribution-of-records-per-hours/snippet.txt: -------------------------------------------------------------------------------- 1 | stats count(*) by queryType, bin(1h) -------------------------------------------------------------------------------- /cloudwatch-insight-route53-dns-resolvers-with-highest-request/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-route53-dns-resolvers-with-highest-request/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Route 53 resolvers with high requests", 3 | "description": "Find the 10 DNS resolvers with the highest number of requests", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["route53"], 6 | "introBox": { 7 | "headline": "How it works", 8 | "text": ["Cloudwatch Log Insight snippet that helps identify DNS resolvers with the highest number of requests"] 9 | }, 10 | "gitHub": { 11 | "template": { 12 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-route53-dns-resolvers-with-highest-request" 13 | } 14 | }, 15 | "snippets": [ 16 | { 17 | "snippetPath": "snippet.txt", 18 | "language": "css" 19 | } 20 | ], 21 | "authors": [ 22 | { 23 | "headline": "Presented by David Boyne", 24 | "name": "David Boyne", 25 | "image": "https://pbs.twimg.com/profile_images/1262283153563140096/DYRDqKg6_400x400.png", 26 | "bio": "Serverless Developer Advocate at AWS", 27 | "linkedin": "", 28 | "twitter": "boyney123" 29 | } 30 | ] 31 | } 32 | -------------------------------------------------------------------------------- /cloudwatch-insight-route53-dns-resolvers-with-highest-request/snippet.txt: -------------------------------------------------------------------------------- 1 | stats count(*) as numRequests by resolverIp 2 | | sort numRequests desc 3 | | limit 10 -------------------------------------------------------------------------------- /cloudwatch-insight-vpc-top-15-byte-transfers/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-vpc-top-15-byte-transfers/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Top 15 byte transfers for hosts on subnet", 3 | "description": "Query for Amazon VPC to find the top 15 byte transfers for hosts on a given subnet.", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["vpc"], 6 | "tags": [ 7 | ], 8 | "introBox": { 9 | "headline": "How it works", 10 | "text": ["Cloudwatch Log Insight snippet that finds the top 15 byte transfers on your VPC for hosts on a given subnet."] 11 | }, 12 | "gitHub": { 13 | "template": { 14 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-vpc-top-15-byte-transfers" 15 | } 16 | }, 17 | "snippets": [ 18 | { 19 | "snippetPath": "snippet.txt", 20 | "language": "css" 21 | } 22 | ], 23 | "authors": [ 24 | { 25 | "headline": "Presented by David Boyne", 26 | "name": "David Boyne", 27 | "image": "https://pbs.twimg.com/profile_images/1262283153563140096/DYRDqKg6_400x400.png", 28 | "bio": "Serverless Developer Advocate at AWS", 29 | "linkedin": "", 30 | "twitter": "boyney123" 31 | } 32 | ] 33 | } 34 | -------------------------------------------------------------------------------- /cloudwatch-insight-vpc-top-15-byte-transfers/snippet.txt: -------------------------------------------------------------------------------- 1 | filter isIpv4InSubnet(srcAddr, "192.0.2.0/24") 2 | | stats sum(bytes) as bytesTransferred by dstAddr 3 | | sort bytesTransferred desc 4 | | limit 15 -------------------------------------------------------------------------------- /cloudwatch-insight-vpc-top-15-packet-transfers/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-insight-vpc-top-15-packet-transfers/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Top 15 packet transfers across hosts", 3 | "description": "Query for Amazon VPC to find the top 15 packet transfers across hosts", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["vpc"], 6 | "tags": [ 7 | ], 8 | "introBox": { 9 | "headline": "How it works", 10 | "text": ["Cloudwatch Log Insight snippet that finds the top 15 packet transfers in your VPC."] 11 | }, 12 | "gitHub": { 13 | "template": { 14 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-insight-vpc-top-15-packet-transfers" 15 | } 16 | }, 17 | "snippets": [ 18 | { 19 | "snippetPath": "snippet.txt", 20 | "language": "css" 21 | } 22 | ], 23 | "authors": [ 24 | { 25 | "headline": "Presented by David Boyne", 26 | "name": "David Boyne", 27 | "image": "https://pbs.twimg.com/profile_images/1262283153563140096/DYRDqKg6_400x400.png", 28 | "bio": "Serverless Developer Advocate at AWS", 29 | "linkedin": "", 30 | "twitter": "boyney123" 31 | } 32 | ] 33 | } 34 | -------------------------------------------------------------------------------- /cloudwatch-insight-vpc-top-15-packet-transfers/snippet.txt: -------------------------------------------------------------------------------- 1 | stats sum(packets) as packetsTransferred by srcAddr, dstAddr 2 | | sort packetsTransferred desc 3 | | limit 15 -------------------------------------------------------------------------------- /cloudwatch-logs-that-are-not-exceptions/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /cloudwatch-logs-that-are-not-exceptions/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Get logs that are not exceptions", 3 | "description": "Query that will return logs that are not exceptions", 4 | "type": "CloudWatch Logs Insights", 5 | "services": [], 6 | "tags": [], 7 | "introBox": { 8 | "headline": "How it works", 9 | "text": ["Cloudwatch Log Insight snippet that returns logs that are not exceptions"] 10 | }, 11 | "gitHub": { 12 | "template": { 13 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/cloudwatch-logs-that-are-not-exceptions" 14 | } 15 | }, 16 | "snippets": [ 17 | { 18 | "snippetPath": "snippet.txt", 19 | "language": "css" 20 | } 21 | ], 22 | "authors": [ 23 | { 24 | "headline": "Presented by David Boyne", 25 | "name": "David Boyne", 26 | "image": "https://pbs.twimg.com/profile_images/1262283153563140096/DYRDqKg6_400x400.png", 27 | "bio": "Serverless Developer Advocate at AWS", 28 | "linkedin": "", 29 | "twitter": "boyney123" 30 | } 31 | ] 32 | } 33 | -------------------------------------------------------------------------------- /cloudwatch-logs-that-are-not-exceptions/snippet.txt: -------------------------------------------------------------------------------- 1 | fields @message | filter @message not like /Exception/ -------------------------------------------------------------------------------- /http-api-parameter-mapping-for-remove-action/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /http-api-parameter-mapping-for-remove-action/snippet.txt: -------------------------------------------------------------------------------- 1 | aws apigatewayv2 update-integration \ 2 | --api-id $API 3 | --integration-id $INTEGRATION_ID 4 | --request-parameters {\"remove:header.custom_headerA\":\"\'\'\"} \ 5 | --response-parameters {\"200\":{\"remove:header.headerB\":\"\'\'\"}} -------------------------------------------------------------------------------- /images/multi-snippet.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/serverless-snippets/HEAD/images/multi-snippet.png -------------------------------------------------------------------------------- /images/single-snippet.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/serverless-snippets/HEAD/images/single-snippet.png -------------------------------------------------------------------------------- /images/tabbed-snippet.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/serverless-snippets/HEAD/images/tabbed-snippet.png -------------------------------------------------------------------------------- /integration-ddb-to-lambda-with-batch-item-handling/example.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | package main 4 | 5 | import ( 6 | "context" 7 | 8 | "github.com/aws/aws-lambda-go/events" 9 | "github.com/aws/aws-lambda-go/lambda" 10 | ) 11 | 12 | type BatchItemFailure struct { 13 | ItemIdentifier string `json:"ItemIdentifier"` 14 | } 15 | 16 | type BatchResult struct { 17 | BatchItemFailures []BatchItemFailure `json:"BatchItemFailures"` 18 | } 19 | 20 | func HandleRequest(ctx context.Context, event events.DynamoDBEvent) (*BatchResult, error) { 21 | var batchItemFailures []BatchItemFailure 22 | 23 | for _, record := range event.Records { 24 | if err := processRecord(record); err != nil { 25 | batchItemFailures = append(batchItemFailures, BatchItemFailure{ 26 | ItemIdentifier: record.Change.SequenceNumber, 27 | }) 28 | } 29 | } 30 | 31 | return &BatchResult{BatchItemFailures: batchItemFailures}, nil 32 | } 33 | 34 | func processRecord(record events.DynamoDBEventRecord) error { 35 | // Your processing logic here 36 | return nil 37 | } 38 | 39 | func main() { 40 | lambda.Start(HandleRequest) 41 | } 42 | -------------------------------------------------------------------------------- /integration-ddb-to-lambda-with-batch-item-handling/example.js: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | export const handler = async (event) => { 4 | const records = event.Records; 5 | let curRecordSequenceNumber = ""; 6 | 7 | for (const record of records) { 8 | try { 9 | // Process your record 10 | curRecordSequenceNumber = record.dynamodb.SequenceNumber; 11 | } catch (e) { 12 | // Return failed record's sequence number 13 | return { batchItemFailures: [{ itemIdentifier: curRecordSequenceNumber }] }; 14 | } 15 | } 16 | 17 | return { batchItemFailures: [] }; 18 | }; 19 | -------------------------------------------------------------------------------- /integration-ddb-to-lambda-with-batch-item-handling/example.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: Apache-2.0 3 | def handler(event, context): 4 | records = event.get("Records") 5 | curRecordSequenceNumber = "" 6 | 7 | for record in records: 8 | try: 9 | # Process your record 10 | curRecordSequenceNumber = record["dynamodb"]["SequenceNumber"] 11 | except Exception as e: 12 | # Return failed record's sequence number 13 | return {"batchItemFailures":[{"itemIdentifier": curRecordSequenceNumber}]} 14 | 15 | return {"batchItemFailures":[]} 16 | -------------------------------------------------------------------------------- /integration-ddb-to-lambda-with-batch-item-handling/example.rb: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: Apache-2.0 3 | def lambda_handler(event:, context:) 4 | records = event["Records"] 5 | cur_record_sequence_number = "" 6 | 7 | records.each do |record| 8 | begin 9 | # Process your record 10 | cur_record_sequence_number = record["dynamodb"]["SequenceNumber"] 11 | rescue StandardError => e 12 | # Return failed record's sequence number 13 | return {"batchItemFailures" => [{"itemIdentifier" => cur_record_sequence_number}]} 14 | end 15 | end 16 | 17 | {"batchItemFailures" => []} 18 | end -------------------------------------------------------------------------------- /integration-ddb-to-lambda-with-batch-item-handling/example.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | import { 4 | DynamoDBBatchResponse, 5 | DynamoDBBatchItemFailure, 6 | DynamoDBStreamEvent, 7 | } from "aws-lambda"; 8 | 9 | export const handler = async ( 10 | event: DynamoDBStreamEvent 11 | ): Promise => { 12 | const batchItemFailures: DynamoDBBatchItemFailure[] = []; 13 | let curRecordSequenceNumber; 14 | 15 | for (const record of event.Records) { 16 | curRecordSequenceNumber = record.dynamodb?.SequenceNumber; 17 | 18 | if (curRecordSequenceNumber) { 19 | batchItemFailures.push({ 20 | itemIdentifier: curRecordSequenceNumber, 21 | }); 22 | } 23 | } 24 | 25 | return { batchItemFailures: batchItemFailures }; 26 | }; 27 | -------------------------------------------------------------------------------- /integration-ddb-to-lambda/Function.cs: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | using System.Text.Json; 4 | using System.Text; 5 | using Amazon.Lambda.Core; 6 | using Amazon.Lambda.DynamoDBEvents; 7 | 8 | // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. 9 | [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] 10 | 11 | namespace AWSLambda_DDB; 12 | 13 | public class Function 14 | { 15 | public void FunctionHandler(DynamoDBEvent dynamoEvent, ILambdaContext context) 16 | { 17 | context.Logger.LogInformation($"Beginning to process {dynamoEvent.Records.Count} records..."); 18 | 19 | foreach (var record in dynamoEvent.Records) 20 | { 21 | context.Logger.LogInformation($"Event ID: {record.EventID}"); 22 | context.Logger.LogInformation($"Event Name: {record.EventName}"); 23 | 24 | context.Logger.LogInformation(JsonSerializer.Serialize(record)); 25 | } 26 | 27 | context.Logger.LogInformation("Stream processing complete."); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /integration-ddb-to-lambda/example.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | package main 4 | 5 | import ( 6 | "context" 7 | "github.com/aws/aws-lambda-go/lambda" 8 | "github.com/aws/aws-lambda-go/events" 9 | "fmt" 10 | ) 11 | 12 | func HandleRequest(ctx context.Context, event events.DynamoDBEvent) (*string, error) { 13 | if len(event.Records) == 0 { 14 | return nil, fmt.Errorf("received empty event") 15 | } 16 | 17 | for _, record := range event.Records { 18 | LogDynamoDBRecord(record) 19 | } 20 | 21 | message := fmt.Sprintf("Records processed: %d", len(event.Records)) 22 | return &message, nil 23 | } 24 | 25 | func main() { 26 | lambda.Start(HandleRequest) 27 | } 28 | 29 | func LogDynamoDBRecord(record events.DynamoDBEventRecord){ 30 | fmt.Println(record.EventID) 31 | fmt.Println(record.EventName) 32 | fmt.Printf("%+v\n", record.Change) 33 | } -------------------------------------------------------------------------------- /integration-ddb-to-lambda/example.java: -------------------------------------------------------------------------------- 1 | import com.amazonaws.services.lambda.runtime.Context; 2 | import com.amazonaws.services.lambda.runtime.RequestHandler; 3 | import com.amazonaws.services.lambda.runtime.events.DynamodbEvent; 4 | import com.amazonaws.services.lambda.runtime.events.DynamodbEvent.DynamodbStreamRecord; 5 | import com.google.gson.Gson; 6 | import com.google.gson.GsonBuilder; 7 | 8 | public class example implements RequestHandler { 9 | 10 | private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); 11 | 12 | @Override 13 | public Void handleRequest(DynamodbEvent event, Context context) { 14 | System.out.println(GSON.toJson(event)); 15 | event.getRecords().forEach(this::logDynamoDBRecord); 16 | return null; 17 | } 18 | 19 | private void logDynamoDBRecord(DynamodbStreamRecord record) { 20 | System.out.println(record.getEventID()); 21 | System.out.println(record.getEventName()); 22 | System.out.println("DynamoDB Record: " + GSON.toJson(record.getDynamodb())); 23 | } 24 | } -------------------------------------------------------------------------------- /integration-ddb-to-lambda/example.js: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | exports.handler = async (event, context) => { 4 | console.log(JSON.stringify(event, null, 2)); 5 | event.Records.forEach(record => { 6 | logDynamoDBRecord(record); 7 | }); 8 | }; 9 | 10 | const logDynamoDBRecord = (record) => { 11 | console.log(record.eventID); 12 | console.log(record.eventName); 13 | console.log(`DynamoDB Record: ${JSON.stringify(record.dynamodb)}`); 14 | }; 15 | -------------------------------------------------------------------------------- /integration-ddb-to-lambda/example.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: Apache-2.0 3 | 4 | import json 5 | 6 | def lambda_handler(event, context): 7 | print(json.dumps(event, indent=2)) 8 | 9 | for record in event['Records']: 10 | log_dynamodb_record(record) 11 | 12 | def log_dynamodb_record(record): 13 | print(record['eventID']) 14 | print(record['eventName']) 15 | print(f"DynamoDB Record: {json.dumps(record['dynamodb'])}") 16 | -------------------------------------------------------------------------------- /integration-ddb-to-lambda/example.rb: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: Apache-2.0 3 | 4 | def lambda_handler(event:, context:) 5 | return 'received empty event' if event['Records'].empty? 6 | 7 | event['Records'].each do |record| 8 | log_dynamodb_record(record) 9 | end 10 | 11 | "Records processed: #{event['Records'].length}" 12 | end 13 | 14 | def log_dynamodb_record(record) 15 | puts record['eventID'] 16 | puts record['eventName'] 17 | puts "DynamoDB Record: #{JSON.generate(record['dynamodb'])}" 18 | end 19 | -------------------------------------------------------------------------------- /integration-ddb-to-lambda/example.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | export const handler = async (event, context) => { 4 | console.log(JSON.stringify(event, null, 2)); 5 | event.Records.forEach(record => { 6 | logDynamoDBRecord(record); 7 | }); 8 | } 9 | const logDynamoDBRecord = (record) => { 10 | console.log(record.eventID); 11 | console.log(record.eventName); 12 | console.log(`DynamoDB Record: ${JSON.stringify(record.dynamodb)}`); 13 | }; -------------------------------------------------------------------------------- /integration-docdb-to-lambda/example.js: -------------------------------------------------------------------------------- 1 | console.log('Loading function'); 2 | exports.handler = async (event, context) => { 3 | event.events.forEach(record => { 4 | logDocumentDBEvent(record); 5 | }); 6 | return 'OK'; 7 | }; 8 | 9 | const logDocumentDBEvent = (record) => { 10 | console.log('Operation type: ' + record.event.operationType); 11 | console.log('db: ' + record.event.ns.db); 12 | console.log('collection: ' + record.event.ns.coll); 13 | console.log('Full document:', JSON.stringify(record.event.fullDocument, null, 2)); 14 | }; 15 | 16 | -------------------------------------------------------------------------------- /integration-docdb-to-lambda/example.php: -------------------------------------------------------------------------------- 1 | logDocumentDBEvent($record['event']); 16 | } 17 | return 'OK'; 18 | } 19 | 20 | private function logDocumentDBEvent($event): void 21 | { 22 | // Extract information from the event record 23 | 24 | $operationType = $event['operationType'] ?? 'Unknown'; 25 | $db = $event['ns']['db'] ?? 'Unknown'; 26 | $collection = $event['ns']['coll'] ?? 'Unknown'; 27 | $fullDocument = $event['fullDocument'] ?? []; 28 | 29 | // Log the event details 30 | 31 | echo "Operation type: $operationType\n"; 32 | echo "Database: $db\n"; 33 | echo "Collection: $collection\n"; 34 | echo "Full document: " . json_encode($fullDocument, JSON_PRETTY_PRINT) . "\n"; 35 | } 36 | } 37 | return new DocumentDBEventHandler(); -------------------------------------------------------------------------------- /integration-docdb-to-lambda/example.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | def lambda_handler(event, context): 4 | for record in event.get('events', []): 5 | log_document_db_event(record) 6 | return 'OK' 7 | 8 | def log_document_db_event(record): 9 | event_data = record.get('event', {}) 10 | operation_type = event_data.get('operationType', 'Unknown') 11 | db = event_data.get('ns', {}).get('db', 'Unknown') 12 | collection = event_data.get('ns', {}).get('coll', 'Unknown') 13 | full_document = event_data.get('fullDocument', {}) 14 | 15 | print(f"Operation type: {operation_type}") 16 | print(f"db: {db}") 17 | print(f"collection: {collection}") 18 | print("Full document:", json.dumps(full_document, indent=2)) -------------------------------------------------------------------------------- /integration-docdb-to-lambda/example.rb: -------------------------------------------------------------------------------- 1 | require 'json' 2 | 3 | def lambda_handler(event:, context:) 4 | event['events'].each do |record| 5 | log_document_db_event(record) 6 | end 7 | 'OK' 8 | end 9 | 10 | def log_document_db_event(record) 11 | event_data = record['event'] || {} 12 | operation_type = event_data['operationType'] || 'Unknown' 13 | db = event_data.dig('ns', 'db') || 'Unknown' 14 | collection = event_data.dig('ns', 'coll') || 'Unknown' 15 | full_document = event_data['fullDocument'] || {} 16 | 17 | puts "Operation type: #{operation_type}" 18 | puts "db: #{db}" 19 | puts "collection: #{collection}" 20 | puts "Full document: #{JSON.pretty_generate(full_document)}" 21 | end -------------------------------------------------------------------------------- /integration-docdb-to-lambda/example.ts: -------------------------------------------------------------------------------- 1 | import { DocumentDBEventRecord, DocumentDBEventSubscriptionContext } from 'aws-lambda'; 2 | 3 | console.log('Loading function'); 4 | 5 | export const handler = async ( 6 | event: DocumentDBEventSubscriptionContext, 7 | context: any 8 | ): Promise => { 9 | event.events.forEach((record: DocumentDBEventRecord) => { 10 | logDocumentDBEvent(record); 11 | }); 12 | return 'OK'; 13 | }; 14 | 15 | const logDocumentDBEvent = (record: DocumentDBEventRecord): void => { 16 | console.log('Operation type: ' + record.event.operationType); 17 | console.log('db: ' + record.event.ns.db); 18 | console.log('collection: ' + record.event.ns.coll); 19 | console.log('Full document:', JSON.stringify(record.event.fullDocument, null, 2)); 20 | }; 21 | -------------------------------------------------------------------------------- /integration-docdb-to-lambda/main.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package main 5 | 6 | import ( 7 | "context" 8 | "encoding/json" 9 | "fmt" 10 | 11 | "github.com/aws/aws-lambda-go/lambda" 12 | ) 13 | 14 | type Event struct { 15 | Events []Record `json:"events"` 16 | } 17 | 18 | type Record struct { 19 | Event struct { 20 | OperationType string `json:"operationType"` 21 | NS struct { 22 | DB string `json:"db"` 23 | Coll string `json:"coll"` 24 | } `json:"ns"` 25 | FullDocument interface{} `json:"fullDocument"` 26 | } `json:"event"` 27 | } 28 | 29 | func main() { 30 | lambda.Start(handler) 31 | } 32 | 33 | func handler(ctx context.Context, event Event) (string, error) { 34 | fmt.Println("Loading function") 35 | for _, record := range event.Events { 36 | logDocumentDBEvent(record) 37 | } 38 | 39 | return "OK", nil 40 | } 41 | 42 | func logDocumentDBEvent(record Record) { 43 | fmt.Printf("Operation type: %s\n", record.Event.OperationType) 44 | fmt.Printf("db: %s\n", record.Event.NS.DB) 45 | fmt.Printf("collection: %s\n", record.Event.NS.Coll) 46 | docBytes, _ := json.MarshalIndent(record.Event.FullDocument, "", " ") 47 | fmt.Printf("Full document: %s\n", string(docBytes)) 48 | } 49 | -------------------------------------------------------------------------------- /integration-kinesis-to-lambda-with-batch-item-handling/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /integration-kinesis-to-lambda-with-batch-item-handling/example.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | package main 4 | 5 | import ( 6 | "context" 7 | "fmt" 8 | "github.com/aws/aws-lambda-go/events" 9 | "github.com/aws/aws-lambda-go/lambda" 10 | ) 11 | 12 | func handler(ctx context.Context, kinesisEvent events.KinesisEvent) (map[string]interface{}, error) { 13 | batchItemFailures := []map[string]interface{}{} 14 | 15 | for _, record := range kinesisEvent.Records { 16 | curRecordSequenceNumber := "" 17 | 18 | // Process your record 19 | if /* Your record processing condition here */ { 20 | curRecordSequenceNumber = record.Kinesis.SequenceNumber 21 | } 22 | 23 | // Add a condition to check if the record processing failed 24 | if curRecordSequenceNumber != "" { 25 | batchItemFailures = append(batchItemFailures, map[string]interface{}{"itemIdentifier": curRecordSequenceNumber}) 26 | } 27 | } 28 | 29 | kinesisBatchResponse := map[string]interface{}{ 30 | "batchItemFailures": batchItemFailures, 31 | } 32 | return kinesisBatchResponse, nil 33 | } 34 | 35 | func main() { 36 | lambda.Start(handler) 37 | } 38 | -------------------------------------------------------------------------------- /integration-kinesis-to-lambda-with-batch-item-handling/example.js: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | exports.handler = async (event, context) => { 4 | for (const record of event.Records) { 5 | try { 6 | console.log(`Processed Kinesis Event - EventID: ${record.eventID}`); 7 | const recordData = await getRecordDataAsync(record.kinesis); 8 | console.log(`Record Data: ${recordData}`); 9 | // TODO: Do interesting work based on the new data 10 | } catch (err) { 11 | console.error(`An error occurred ${err}`); 12 | /* Since we are working with streams, we can return the failed item immediately. 13 | Lambda will immediately begin to retry processing from this failed item onwards. */ 14 | return { 15 | batchItemFailures: [{ itemIdentifier: record.kinesis.sequenceNumber }], 16 | }; 17 | } 18 | } 19 | console.log(`Successfully processed ${event.Records.length} records.`); 20 | return { batchItemFailures: [] }; 21 | }; 22 | 23 | async function getRecordDataAsync(payload) { 24 | var data = Buffer.from(payload.data, "base64").toString("utf-8"); 25 | await Promise.resolve(1); //Placeholder for actual async work 26 | return data; 27 | } 28 | -------------------------------------------------------------------------------- /integration-kinesis-to-lambda-with-batch-item-handling/example.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: Apache-2.0 3 | def handler(event, context): 4 | records = event.get("Records") 5 | curRecordSequenceNumber = "" 6 | 7 | for record in records: 8 | try: 9 | # Process your record 10 | curRecordSequenceNumber = record["kinesis"]["sequenceNumber"] 11 | except Exception as e: 12 | # Return failed record's sequence number 13 | return {"batchItemFailures":[{"itemIdentifier": curRecordSequenceNumber}]} 14 | 15 | return {"batchItemFailures":[]} 16 | -------------------------------------------------------------------------------- /integration-kinesis-to-lambda-with-batch-item-handling/example.rb: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: Apache-2.0 3 | require 'aws-sdk' 4 | 5 | def lambda_handler(event:, context:) 6 | batch_item_failures = [] 7 | 8 | event['Records'].each do |record| 9 | begin 10 | puts "Processed Kinesis Event - EventID: #{record['eventID']}" 11 | record_data = get_record_data_async(record['kinesis']) 12 | puts "Record Data: #{record_data}" 13 | # TODO: Do interesting work based on the new data 14 | rescue StandardError => err 15 | puts "An error occurred #{err}" 16 | # Since we are working with streams, we can return the failed item immediately. 17 | # Lambda will immediately begin to retry processing from this failed item onwards. 18 | return { batchItemFailures: [{ itemIdentifier: record['kinesis']['sequenceNumber'] }] } 19 | end 20 | end 21 | 22 | puts "Successfully processed #{event['Records'].length} records." 23 | { batchItemFailures: batch_item_failures } 24 | end 25 | 26 | def get_record_data_async(payload) 27 | data = Base64.decode64(payload['data']).force_encoding('utf-8') 28 | # Placeholder for actual async work 29 | sleep(1) 30 | data 31 | end -------------------------------------------------------------------------------- /integration-kinesis-to-lambda/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /integration-kinesis-to-lambda/example.js: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | exports.handler = async (event, context) => { 4 | for (const record of event.Records) { 5 | try { 6 | console.log(`Processed Kinesis Event - EventID: ${record.eventID}`); 7 | const recordData = await getRecordDataAsync(record.kinesis); 8 | console.log(`Record Data: ${recordData}`); 9 | // TODO: Do interesting work based on the new data 10 | } catch (err) { 11 | console.error(`An error occurred ${err}`); 12 | throw err; 13 | } 14 | } 15 | console.log(`Successfully processed ${event.Records.length} records.`); 16 | }; 17 | 18 | async function getRecordDataAsync(payload) { 19 | var data = Buffer.from(payload.data, "base64").toString("utf-8"); 20 | await Promise.resolve(1); //Placeholder for actual async work 21 | return data; 22 | } 23 | -------------------------------------------------------------------------------- /integration-kinesis-to-lambda/example.rb: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: Apache-2.0 3 | require 'aws-sdk' 4 | 5 | def lambda_handler(event:, context:) 6 | event['Records'].each do |record| 7 | begin 8 | puts "Processed Kinesis Event - EventID: #{record['eventID']}" 9 | record_data = get_record_data_async(record['kinesis']) 10 | puts "Record Data: #{record_data}" 11 | # TODO: Do interesting work based on the new data 12 | rescue => err 13 | $stderr.puts "An error occurred #{err}" 14 | raise err 15 | end 16 | end 17 | puts "Successfully processed #{event['Records'].length} records." 18 | end 19 | 20 | def get_record_data_async(payload) 21 | data = Base64.decode64(payload['data']).force_encoding('UTF-8') 22 | # Placeholder for actual async work 23 | # You can use Ruby's asynchronous programming tools like async/await or fibers here. 24 | return data 25 | end -------------------------------------------------------------------------------- /integration-kinesis-to-lambda/main.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | package main 4 | 5 | import ( 6 | "context" 7 | "log" 8 | 9 | "github.com/aws/aws-lambda-go/events" 10 | "github.com/aws/aws-lambda-go/lambda" 11 | ) 12 | 13 | func handler(ctx context.Context, kinesisEvent events.KinesisEvent) error { 14 | if len(kinesisEvent.Records) == 0 { 15 | log.Printf("empty Kinesis event received") 16 | return nil 17 | } 18 | 19 | for _, record := range kinesisEvent.Records { 20 | log.Printf("processed Kinesis event with EventId: %v", record.EventID) 21 | recordDataBytes := record.Kinesis.Data 22 | recordDataText := string(recordDataBytes) 23 | log.Printf("record data: %v", recordDataText) 24 | // TODO: Do interesting work based on the new data 25 | } 26 | log.Printf("successfully processed %v records", len(kinesisEvent.Records)) 27 | return nil 28 | } 29 | 30 | func main() { 31 | lambda.Start(handler) 32 | } 33 | -------------------------------------------------------------------------------- /integration-kinesis-to-lambda/main.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: Apache-2.0 3 | import base64 4 | def lambda_handler(event, context): 5 | 6 | for record in event['Records']: 7 | try: 8 | print(f"Processed Kinesis Event - EventID: {record['eventID']}") 9 | record_data = base64.b64decode(record['kinesis']['data']).decode('utf-8') 10 | print(f"Record Data: {record_data}") 11 | # TODO: Do interesting work based on the new data 12 | except Exception as e: 13 | print(f"An error occurred {e}") 14 | raise e 15 | print(f"Successfully processed {len(event['Records'])} records.") 16 | -------------------------------------------------------------------------------- /integration-msk-to-lambda/Example.java: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import com.amazonaws.services.lambda.runtime.Context; 5 | import com.amazonaws.services.lambda.runtime.RequestHandler; 6 | import com.amazonaws.services.lambda.runtime.events.KafkaEvent; 7 | import com.amazonaws.services.lambda.runtime.events.KafkaEvent.KafkaEventRecord; 8 | 9 | import java.util.Base64; 10 | import java.util.Map; 11 | 12 | public class Example implements RequestHandler { 13 | 14 | @Override 15 | public Void handleRequest(KafkaEvent event, Context context) { 16 | for (Map.Entry> entry : event.getRecords().entrySet()) { 17 | String key = entry.getKey(); 18 | System.out.println("Key: " + key); 19 | 20 | for (KafkaEventRecord record : entry.getValue()) { 21 | System.out.println("Record: " + record); 22 | 23 | byte[] value = Base64.getDecoder().decode(record.getValue()); 24 | String message = new String(value); 25 | System.out.println("Message: " + message); 26 | } 27 | } 28 | 29 | return null; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /integration-msk-to-lambda/Function.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | using Amazon.Lambda.Core; 3 | using Amazon.Lambda.KafkaEvents; 4 | 5 | 6 | // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. 7 | [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] 8 | 9 | namespace MSKLambda; 10 | 11 | public class Function 12 | { 13 | 14 | 15 | /// The event for the Lambda function handler to process. 16 | /// The ILambdaContext that provides methods for logging and describing the Lambda environment. 17 | /// 18 | public void FunctionHandler(KafkaEvent evnt, ILambdaContext context) 19 | { 20 | 21 | foreach (var record in evnt.Records) 22 | { 23 | Console.WriteLine("Key:" + record.Key); 24 | foreach (var eventRecord in record.Value) 25 | { 26 | var valueBytes = eventRecord.Value.ToArray(); 27 | var valueText = Encoding.UTF8.GetString(valueBytes); 28 | 29 | Console.WriteLine("Message:" + valueText); 30 | } 31 | } 32 | } 33 | 34 | 35 | } 36 | -------------------------------------------------------------------------------- /integration-msk-to-lambda/example.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | package main 5 | 6 | import ( 7 | "encoding/base64" 8 | "fmt" 9 | 10 | "github.com/aws/aws-lambda-go/events" 11 | "github.com/aws/aws-lambda-go/lambda" 12 | ) 13 | 14 | func handler(event events.KafkaEvent) { 15 | for key, records := range event.Records { 16 | fmt.Println("Key:", key) 17 | 18 | for _, record := range records { 19 | fmt.Println("Record:", record) 20 | 21 | decodedValue, _ := base64.StdEncoding.DecodeString(record.Value) 22 | message := string(decodedValue) 23 | fmt.Println("Message:", message) 24 | } 25 | } 26 | } 27 | 28 | func main() { 29 | lambda.Start(handler) 30 | } -------------------------------------------------------------------------------- /integration-msk-to-lambda/example.js: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | exports.handler = async (event) => { 5 | // Iterate through keys 6 | for (let key in event.records) { 7 | console.log('Key: ', key) 8 | // Iterate through records 9 | event.records[key].map((record) => { 10 | console.log('Record: ', record) 11 | // Decode base64 12 | const msg = Buffer.from(record.value, 'base64').toString() 13 | console.log('Message:', msg) 14 | }) 15 | } 16 | } -------------------------------------------------------------------------------- /integration-msk-to-lambda/example.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: Apache-2.0 3 | 4 | import base64 5 | 6 | def lambda_handler(event, context): 7 | # Iterate through keys 8 | for key in event['records']: 9 | print('Key:', key) 10 | # Iterate through records 11 | for record in event['records'][key]: 12 | print('Record:', record) 13 | # Decode base64 14 | msg = base64.b64decode(record['value']).decode('utf-8') 15 | print('Message:', msg) -------------------------------------------------------------------------------- /integration-msk-to-lambda/example.rb: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | require 'base64' 5 | 6 | def lambda_handler(event:, context:) 7 | # Iterate through keys 8 | event['records'].each do |key, records| 9 | puts "Key: #{key}" 10 | 11 | # Iterate through records 12 | records.each do |record| 13 | puts "Record: #{record}" 14 | 15 | # Decode base64 16 | msg = Base64.decode64(record['value']) 17 | puts "Message: #{msg}" 18 | end 19 | end 20 | end -------------------------------------------------------------------------------- /integration-msk-to-lambda/example.ts: -------------------------------------------------------------------------------- 1 | import { MSKEvent, Context } from "aws-lambda"; 2 | import { Buffer } from "buffer"; 3 | import { Logger } from "@aws-lambda-powertools/logger"; 4 | 5 | const logger = new Logger({ 6 | logLevel: "INFO", 7 | serviceName: "msk-handler-sample", 8 | }); 9 | 10 | export const handler = async ( 11 | event: MSKEvent, 12 | context: Context 13 | ): Promise => { 14 | for (const [topic, topicRecords] of Object.entries(event.records)) { 15 | logger.info(`Processing key: ${topic}`); 16 | 17 | // Process each record in the partition 18 | for (const record of topicRecords) { 19 | try { 20 | // Decode the message value from base64 21 | const decodedMessage = Buffer.from(record.value, 'base64').toString(); 22 | 23 | logger.info({ 24 | message: decodedMessage 25 | }); 26 | } 27 | catch (error) { 28 | logger.error('Error processing event', { error }); 29 | throw error; 30 | } 31 | }; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /integration-s3-to-lambda/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /integration-s3-to-lambda/example.js: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | import { S3Client, HeadObjectCommand } from "@aws-sdk/client-s3"; 4 | 5 | const client = new S3Client(); 6 | 7 | export const handler = async (event, context) => { 8 | 9 | // Get the object from the event and show its content type 10 | const bucket = event.Records[0].s3.bucket.name; 11 | const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); 12 | 13 | try { 14 | const { ContentType } = await client.send(new HeadObjectCommand({ 15 | Bucket: bucket, 16 | Key: key, 17 | })); 18 | 19 | console.log('CONTENT TYPE:', ContentType); 20 | return ContentType; 21 | 22 | } catch (err) { 23 | console.log(err); 24 | const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`; 25 | console.log(message); 26 | throw new Error(message); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /integration-s3-to-lambda/example.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: Apache-2.0 3 | import json 4 | import urllib.parse 5 | import boto3 6 | 7 | print('Loading function') 8 | 9 | s3 = boto3.client('s3') 10 | 11 | 12 | def lambda_handler(event, context): 13 | #print("Received event: " + json.dumps(event, indent=2)) 14 | 15 | # Get the object from the event and show its content type 16 | bucket = event['Records'][0]['s3']['bucket']['name'] 17 | key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8') 18 | try: 19 | response = s3.get_object(Bucket=bucket, Key=key) 20 | print("CONTENT TYPE: " + response['ContentType']) 21 | return response['ContentType'] 22 | except Exception as e: 23 | print(e) 24 | print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket)) 25 | raise e 26 | -------------------------------------------------------------------------------- /integration-s3-to-lambda/example.rb: -------------------------------------------------------------------------------- 1 | require 'json' 2 | require 'uri' 3 | require 'aws-sdk' 4 | 5 | puts 'Loading function' 6 | 7 | def lambda_handler(event:, context:) 8 | s3 = Aws::S3::Client.new(region: 'region') # Your AWS region 9 | # puts "Received event: #{JSON.dump(event)}" 10 | 11 | # Get the object from the event and show its content type 12 | bucket = event['Records'][0]['s3']['bucket']['name'] 13 | key = URI.decode_www_form_component(event['Records'][0]['s3']['object']['key'], Encoding::UTF_8) 14 | begin 15 | response = s3.get_object(bucket: bucket, key: key) 16 | puts "CONTENT TYPE: #{response.content_type}" 17 | return response.content_type 18 | rescue StandardError => e 19 | puts e.message 20 | puts "Error getting object #{key} from bucket #{bucket}. Make sure they exist and your bucket is in the same region as this function." 21 | raise e 22 | end 23 | end 24 | -------------------------------------------------------------------------------- /integration-s3-to-lambda/example.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | import { S3Event } from 'aws-lambda'; 4 | import { S3Client, HeadObjectCommand } from '@aws-sdk/client-s3'; 5 | 6 | const s3 = new S3Client({ region: process.env.AWS_REGION }); 7 | 8 | export const handler = async (event: S3Event): Promise => { 9 | // Get the object from the event and show its content type 10 | const bucket = event.Records[0].s3.bucket.name; 11 | const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); 12 | const params = { 13 | Bucket: bucket, 14 | Key: key, 15 | }; 16 | try { 17 | const { ContentType } = await s3.send(new HeadObjectCommand(params)); 18 | console.log('CONTENT TYPE:', ContentType); 19 | return ContentType; 20 | } catch (err) { 21 | console.log(err); 22 | const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`; 23 | console.log(message); 24 | throw new Error(message); 25 | } 26 | }; -------------------------------------------------------------------------------- /integration-s3-to-lambda/main.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | package main 4 | 5 | import ( 6 | "context" 7 | "log" 8 | 9 | "github.com/aws/aws-lambda-go/events" 10 | "github.com/aws/aws-lambda-go/lambda" 11 | "github.com/aws/aws-sdk-go-v2/config" 12 | "github.com/aws/aws-sdk-go-v2/service/s3" 13 | ) 14 | 15 | func handler(ctx context.Context, s3Event events.S3Event) error { 16 | sdkConfig, err := config.LoadDefaultConfig(ctx) 17 | if err != nil { 18 | log.Printf("failed to load default config: %s", err) 19 | return err 20 | } 21 | s3Client := s3.NewFromConfig(sdkConfig) 22 | 23 | for _, record := range s3Event.Records { 24 | bucket := record.S3.Bucket.Name 25 | key := record.S3.Object.URLDecodedKey 26 | headOutput, err := s3Client.HeadObject(ctx, &s3.HeadObjectInput{ 27 | Bucket: &bucket, 28 | Key: &key, 29 | }) 30 | if err != nil { 31 | log.Printf("error getting head of object %s/%s: %s", bucket, key, err) 32 | return err 33 | } 34 | log.Printf("successfully retrieved %s/%s of type %s", bucket, key, *headOutput.ContentType) 35 | } 36 | 37 | return nil 38 | } 39 | 40 | func main() { 41 | lambda.Start(handler) 42 | } 43 | -------------------------------------------------------------------------------- /integration-sns-to-lambda/Function.cs: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | using Amazon.Lambda.Core; 4 | using Amazon.Lambda.SNSEvents; 5 | 6 | 7 | // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. 8 | [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] 9 | 10 | namespace SnsIntegration; 11 | 12 | public class Function 13 | { 14 | public async Task FunctionHandler(SNSEvent evnt, ILambdaContext context) 15 | { 16 | foreach (var record in evnt.Records) 17 | { 18 | await ProcessRecordAsync(record, context); 19 | } 20 | context.Logger.LogInformation("done"); 21 | } 22 | 23 | private async Task ProcessRecordAsync(SNSEvent.SNSRecord record, ILambdaContext context) 24 | { 25 | try 26 | { 27 | context.Logger.LogInformation($"Processed record {record.Sns.Message}"); 28 | 29 | // TODO: Do interesting work based on the new message 30 | await Task.CompletedTask; 31 | } 32 | catch (Exception e) 33 | { 34 | //You can use Dead Letter Queue to handle failures. By configuring a Lambda DLQ. 35 | context.Logger.LogError($"An error occurred"); 36 | throw; 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /integration-sns-to-lambda/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /integration-sns-to-lambda/example.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | package main 4 | 5 | import ( 6 | "context" 7 | "fmt" 8 | 9 | "github.com/aws/aws-lambda-go/events" 10 | "github.com/aws/aws-lambda-go/lambda" 11 | ) 12 | 13 | func handler(ctx context.Context, snsEvent events.SNSEvent) { 14 | for _, record := range snsEvent.Records { 15 | processMessage(record) 16 | } 17 | fmt.Println("done") 18 | } 19 | 20 | func processMessage(record events.SNSEventRecord) { 21 | message := record.SNS.Message 22 | fmt.Printf("Processed message: %s\n", message) 23 | // TODO: Process your record here 24 | } 25 | 26 | func main() { 27 | lambda.Start(handler) 28 | } 29 | -------------------------------------------------------------------------------- /integration-sns-to-lambda/example.js: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | exports.handler = async (event, context) => { 4 | for (const record of event.Records) { 5 | await processMessageAsync(record); 6 | } 7 | console.info("done"); 8 | }; 9 | 10 | async function processMessageAsync(record) { 11 | try { 12 | const message = JSON.stringify(record.Sns.Message); 13 | console.log(`Processed message ${message}`); 14 | await Promise.resolve(1); //Placeholder for actual async work 15 | } catch (err) { 16 | console.error("An error occurred"); 17 | throw err; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /integration-sns-to-lambda/example.php: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | getRecords() as $record) { 25 | $message = $record->getMessage(); 26 | 27 | // TODO: Implement your custom processing logic here 28 | // Any exception thrown will be logged and the invocation will be marked as failed 29 | 30 | echo "Processed Message: $message" . PHP_EOL; 31 | } 32 | } 33 | } 34 | 35 | return new Handler(); 36 | -------------------------------------------------------------------------------- /integration-sns-to-lambda/example.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: Apache-2.0 3 | def lambda_handler(event, context): 4 | for record in event['Records']: 5 | process_message(record) 6 | print("done") 7 | 8 | def process_message(record): 9 | try: 10 | message = record['Sns']['Message'] 11 | print(f"Processed message {message}") 12 | # TODO; Process your record here 13 | 14 | except Exception as e: 15 | print("An error occurred") 16 | raise e 17 | -------------------------------------------------------------------------------- /integration-sns-to-lambda/example.rb: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: Apache-2.0 3 | def lambda_handler(event:, context:) 4 | event['Records'].map { |record| process_message(record) } 5 | end 6 | 7 | def process_message(record) 8 | message = record['Sns']['Message'] 9 | puts("Processing message: #{message}") 10 | rescue StandardError => e 11 | puts("Error processing message: #{e}") 12 | raise 13 | end 14 | -------------------------------------------------------------------------------- /integration-sns-to-lambda/example.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | import { SNSEvent, Context, SNSHandler, SNSEventRecord } from "aws-lambda"; 4 | 5 | export const functionHandler: SNSHandler = async ( 6 | event: SNSEvent, 7 | context: Context 8 | ): Promise => { 9 | for (const record of event.Records) { 10 | await processMessageAsync(record); 11 | } 12 | console.info("done"); 13 | }; 14 | 15 | async function processMessageAsync(record: SNSEventRecord): Promise { 16 | try { 17 | const message: string = JSON.stringify(record.Sns.Message); 18 | console.log(`Processed message ${message}`); 19 | await Promise.resolve(1); //Placeholder for actual async work 20 | } catch (err) { 21 | console.error("An error occurred"); 22 | throw err; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /integration-sqs-to-lambda-with-batch-item-handling/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /integration-sqs-to-lambda-with-batch-item-handling/example.js: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | exports.handler = async (event, context) => { 4 | const batchItemFailures = []; 5 | if (event.Records.length == 0){ 6 | console.log('Empty SQS Event received'); 7 | return { batchItemFailures }; 8 | } 9 | for(const message of event.Records){ 10 | const result = await processMessageAsync(message); 11 | if(result !== null){ 12 | batchItemFailures.push(result); 13 | } 14 | } 15 | return { batchItemFailures }; 16 | }; 17 | 18 | async function processMessageAsync(message) { 19 | try { 20 | console.log(`Processed message ${message.body}`); 21 | // TODO: Do interesting work based on the new message 22 | await Promise.resolve(1); //Placeholder for actual async work 23 | return null; 24 | } catch (err) { 25 | console.error(`An error occurred while processing ${message} - Error: ${err.message}`); 26 | return { itemIdentifier: message.messageId }; 27 | } 28 | } -------------------------------------------------------------------------------- /integration-sqs-to-lambda-with-batch-item-handling/example.rb: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: Apache-2.0 3 | require 'json' 4 | 5 | def lambda_handler(event:, context:) 6 | if event 7 | batch_item_failures = [] 8 | sqs_batch_response = {} 9 | 10 | event["Records"].each do |record| 11 | begin 12 | # process message 13 | rescue StandardError => e 14 | batch_item_failures << {"itemIdentifier" => record['messageId']} 15 | end 16 | end 17 | 18 | sqs_batch_response["batchItemFailures"] = batch_item_failures 19 | return sqs_batch_response 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /integration-sqs-to-lambda/Function.cs: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | using Amazon.Lambda.Core; 4 | using Amazon.Lambda.SQSEvents; 5 | 6 | 7 | // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. 8 | [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] 9 | 10 | namespace SqsIntegrationSampleCode 11 | { 12 | public async Task FunctionHandler(SQSEvent evnt, ILambdaContext context) 13 | { 14 | foreach (var message in evnt.Records) 15 | { 16 | await ProcessMessageAsync(message, context); 17 | } 18 | 19 | context.Logger.LogInformation("done"); 20 | } 21 | 22 | private async Task ProcessMessageAsync(SQSEvent.SQSMessage message, ILambdaContext context) 23 | { 24 | try 25 | { 26 | context.Logger.LogInformation($"Processed message {message.Body}"); 27 | 28 | // TODO: Do interesting work based on the new message 29 | await Task.CompletedTask; 30 | } 31 | catch (Exception e) 32 | { 33 | //You can use Dead Letter Queue to handle failures. By configuring a Lambda DLQ. 34 | context.Logger.LogError($"An error occurred"); 35 | throw; 36 | } 37 | 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /integration-sqs-to-lambda/Function.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | package integration_sqs_to_lambda 4 | 5 | import ( 6 | "fmt" 7 | "github.com/aws/aws-lambda-go/events" 8 | "github.com/aws/aws-lambda-go/lambda" 9 | ) 10 | 11 | func handler(event events.SQSEvent) error { 12 | for _, record := range event.Records { 13 | err := processMessage(record) 14 | if err != nil { 15 | return err 16 | } 17 | } 18 | fmt.Println("done") 19 | return nil 20 | } 21 | 22 | func processMessage(record events.SQSMessage) error { 23 | fmt.Printf("Processed message %s\n", record.Body) 24 | // TODO: Do interesting work based on the new message 25 | return nil 26 | } 27 | 28 | func main() { 29 | lambda.Start(handler) 30 | } 31 | -------------------------------------------------------------------------------- /integration-sqs-to-lambda/Function.java: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | import com.amazonaws.services.lambda.runtime.Context; 4 | import com.amazonaws.services.lambda.runtime.RequestHandler; 5 | import com.amazonaws.services.lambda.runtime.events.SQSEvent; 6 | import com.amazonaws.services.lambda.runtime.events.SQSEvent.SQSMessage; 7 | 8 | public class Function implements RequestHandler { 9 | @Override 10 | public Void handleRequest(SQSEvent sqsEvent, Context context) { 11 | for (SQSMessage msg : sqsEvent.getRecords()) { 12 | processMessage(msg, context); 13 | } 14 | context.getLogger().log("done"); 15 | return null; 16 | } 17 | 18 | private void processMessage(SQSMessage msg, Context context) { 19 | try { 20 | context.getLogger().log("Processed message " + msg.getBody()); 21 | 22 | // TODO: Do interesting work based on the new message 23 | 24 | } catch (Exception e) { 25 | context.getLogger().log("An error occurred"); 26 | throw e; 27 | } 28 | 29 | } 30 | } -------------------------------------------------------------------------------- /integration-sqs-to-lambda/Function.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: Apache-2.0 3 | def lambda_handler(event, context): 4 | for message in event['Records']: 5 | process_message(message) 6 | print("done") 7 | 8 | def process_message(message): 9 | try: 10 | print(f"Processed message {message['body']}") 11 | # TODO: Do interesting work based on the new message 12 | except Exception as err: 13 | print("An error occurred") 14 | raise err 15 | -------------------------------------------------------------------------------- /integration-sqs-to-lambda/Function.rb: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: Apache-2.0 3 | def lambda_handler(event:, context:) 4 | event['Records'].each do |message| 5 | process_message(message) 6 | end 7 | puts "done" 8 | end 9 | 10 | def process_message(message) 11 | begin 12 | puts "Processed message #{message['body']}" 13 | # TODO: Do interesting work based on the new message 14 | rescue StandardError => err 15 | puts "An error occurred" 16 | raise err 17 | end 18 | end -------------------------------------------------------------------------------- /integration-sqs-to-lambda/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /integration-sqs-to-lambda/example.js: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | exports.handler = async (event, context) => { 4 | for (const message of event.Records) { 5 | await processMessageAsync(message); 6 | } 7 | console.info("done"); 8 | }; 9 | 10 | async function processMessageAsync(message) { 11 | try { 12 | console.log(`Processed message ${message.body}`); 13 | // TODO: Do interesting work based on the new message 14 | await Promise.resolve(1); //Placeholder for actual async work 15 | } catch (err) { 16 | console.error("An error occurred"); 17 | throw err; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /integration-sqs-to-lambda/example.php: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | logger = $logger; 21 | } 22 | 23 | /** 24 | * @throws InvalidLambdaEvent 25 | */ 26 | public function handleSqs(SqsEvent $event, Context $context): void 27 | { 28 | foreach ($event->getRecords() as $record) { 29 | $body = $record->getBody(); 30 | // TODO: Do interesting work based on the new message 31 | } 32 | } 33 | } 34 | 35 | $logger = new StderrLogger(); 36 | return new Handler($logger); 37 | -------------------------------------------------------------------------------- /integration-sqs-to-lambda/example.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | import { SQSEvent, Context, SQSHandler, SQSRecord } from "aws-lambda"; 4 | 5 | export const functionHandler: SQSHandler = async ( 6 | event: SQSEvent, 7 | context: Context 8 | ): Promise => { 9 | for (const message of event.Records) { 10 | await processMessageAsync(message); 11 | } 12 | console.info("done"); 13 | }; 14 | 15 | async function processMessageAsync(message: SQSRecord): Promise { 16 | try { 17 | console.log(`Processed message ${message.body}`); 18 | // TODO: Do interesting work based on the new message 19 | await Promise.resolve(1); //Placeholder for actual async work 20 | } catch (err) { 21 | console.error("An error occurred"); 22 | throw err; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /integration-sqs-to-lambda/main.rs: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | use aws_lambda_events::event::sqs::SqsEvent; 4 | use lambda_runtime::{run, service_fn, Error, LambdaEvent}; 5 | 6 | async fn function_handler(event: LambdaEvent) -> Result<(), Error> { 7 | event.payload.records.iter().for_each(|record| { 8 | // process the record 9 | tracing::info!("Message body: {}", record.body.as_deref().unwrap_or_default()) 10 | }); 11 | 12 | Ok(()) 13 | } 14 | 15 | #[tokio::main] 16 | async fn main() -> Result<(), Error> { 17 | tracing_subscriber::fmt() 18 | .with_max_level(tracing::Level::INFO) 19 | // disable printing the name of the module in every log line. 20 | .with_target(false) 21 | // disabling time is handy because CloudWatch will add the ingestion time. 22 | .without_time() 23 | .init(); 24 | 25 | run(service_fn(function_handler)).await 26 | } -------------------------------------------------------------------------------- /lambda-connect-opensearch/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /lambda-edge-list-functions/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /lambda-edge-list-functions/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "lambda-list-edge-functions-from-region", 3 | "description": "Using CLI to list Lambda@Edge functions replicated from a particular region", 4 | "type": "Integration", 5 | "services": ["lambda"], 6 | "tags": [], 7 | "languages": ["aws cli"], 8 | "introBox": { 9 | "headline": "How it works", 10 | "text": [ 11 | "[This AWS CLI command will list only the Lambda@Edge function replicated from the master region that is configured in cli]" 12 | ] 13 | }, 14 | "gitHub": { 15 | "template": { 16 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/lambda-edge-list-functions" 17 | } 18 | }, 19 | "snippets": [ 20 | { 21 | "title": "List the Lambda@Edge functions", 22 | "snippetPath": "snippet.txt", 23 | "language": "aws cli" 24 | } 25 | ], 26 | "authors": [ 27 | { 28 | "headline": "Presented by Surya Dulla", 29 | "name": "Surya Dulla", 30 | "image": "https://media.licdn.com/dms/image/C4E03AQGAY8pmzboeow/profile-displayphoto-shrink_200_200/0/1562613473789?e=1681344000&v=beta&t=fOrFY98O69OLXLz5vjTsA3UWISAwJ37MeN_As6EP3gU", 31 | "bio": "DevOps Engineer at AWS, Advocate for Cloud technology", 32 | "linkedin": "surya-tejaswi-dulla-54b0b188", 33 | } 34 | ] 35 | } -------------------------------------------------------------------------------- /lambda-edge-list-functions/snippet.txt: -------------------------------------------------------------------------------- 1 | aws lambda list-functions --master-region us-east-1 --function-version ALL -------------------------------------------------------------------------------- /lambda-function-connect-memorydb-iam/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /lambda-function-connect-rds-iam/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /lambda-function-connect-rds-iam/example.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | import boto3 4 | import pymysql 5 | 6 | # RDS settings 7 | proxy_host_name = os.environ['PROXY_HOST_NAME'] 8 | port = int(os.environ['PORT']) 9 | db_name = os.environ['DB_NAME'] 10 | db_user_name = os.environ['DB_USER_NAME'] 11 | aws_region = os.environ['AWS_REGION'] 12 | 13 | 14 | # Fetch RDS Auth Token 15 | def get_auth_token(): 16 | client = boto3.client('rds') 17 | token = client.generate_db_auth_token( 18 | DBHostname=proxy_host_name, 19 | Port=port 20 | DBUsername=db_user_name 21 | Region=aws_region 22 | ) 23 | return token 24 | 25 | def lambda_handler(event, context): 26 | token = get_auth_token() 27 | try: 28 | connection = pymysql.connect( 29 | host=proxy_host_name, 30 | user=db_user_name, 31 | password=token, 32 | db=db_name, 33 | port=port, 34 | ssl={'ca': 'Amazon RDS'} # Ensure you have the CA bundle for SSL connection 35 | ) 36 | 37 | with connection.cursor() as cursor: 38 | cursor.execute('SELECT %s + %s AS sum', (3, 2)) 39 | result = cursor.fetchone() 40 | 41 | return result 42 | 43 | except Exception as e: 44 | return (f"Error: {str(e)}") # Return an error message if an exception occurs 45 | -------------------------------------------------------------------------------- /lambda-function-convert-s3-storageclass/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /lambda-function-convert-s3-storageclass/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Lambda function to convert S3 storage class", 3 | "description": "This function will help to convert your existing S3 storage class to the defined destination storage class.", 4 | "type": "Integration", 5 | "services": ["lambda"], 6 | "tags": ["S3"], 7 | "languages": ["Python"], 8 | "introBox": { 9 | "headline": "How it works", 10 | "text": [ 11 | "This snipped creates a Lambda function in Python helps to convert your existing S3 storage class to the defined destination storage class." 12 | ] 13 | }, 14 | "gitHub": { 15 | "template": { 16 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/lambda-function-convert-s3-storageclass" 17 | } 18 | }, 19 | "snippets": [ 20 | { 21 | "title": "Copy the code into Lambda", 22 | "snippetPath": "snippet.txt", 23 | "language": "py" 24 | } 25 | ], 26 | "authors": [ 27 | { 28 | "headline": "Presented by Arun Thangavel", 29 | "name": "Arun Thangavel", 30 | "image": "https://avatars.githubusercontent.com/u/4443455?s=400&u=d78480fcb9f02a5405951fc1360940884bf9a0f7&v=4", 31 | "bio": "Solutions Architect, Worldwide Public Sector at AWS", 32 | "linkedin": "thangavelarun", 33 | "twitter": "arunt4ever" 34 | } 35 | ] 36 | } 37 | -------------------------------------------------------------------------------- /lambda-function-invoke-vpc-lattice-service/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /lambda-function-kafka-consumer-glue-schema-registry/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /lambda-function-retrieve-deleted-s3-versioned-objects/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /lambda-function-sqs-report-batch-item-failures/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /lambda-function-sqs-report-batch-item-failures/example.go: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | package main 4 | 5 | import ( 6 | "context" 7 | "encoding/json" 8 | "fmt" 9 | "github.com/aws/aws-lambda-go/events" 10 | "github.com/aws/aws-lambda-go/lambda" 11 | ) 12 | 13 | func handler(ctx context.Context, sqsEvent events.SQSEvent) (map[string]interface{}, error) { 14 | batchItemFailures := []map[string]interface{}{} 15 | 16 | for _, message := range sqsEvent.Records { 17 | 18 | if /* Your message processing condition here */ { 19 | batchItemFailures = append(batchItemFailures, map[string]interface{}{"itemIdentifier": message.MessageId}) 20 | } 21 | } 22 | 23 | sqsBatchResponse := map[string]interface{}{ 24 | "batchItemFailures": batchItemFailures, 25 | } 26 | return sqsBatchResponse, nil 27 | } 28 | 29 | func main() { 30 | lambda.Start(handler) 31 | } 32 | -------------------------------------------------------------------------------- /lambda-function-sqs-report-batch-item-failures/example.java: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | import com.amazonaws.services.lambda.runtime.Context; 4 | import com.amazonaws.services.lambda.runtime.RequestHandler; 5 | import com.amazonaws.services.lambda.runtime.events.SQSEvent; 6 | import com.amazonaws.services.lambda.runtime.events.SQSBatchResponse; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | public class ProcessSQSMessageBatch implements RequestHandler { 12 | @Override 13 | public SQSBatchResponse handleRequest(SQSEvent sqsEvent, Context context) { 14 | List batchItemFailures = new ArrayList(); 15 | 16 | for (SQSEvent.SQSMessage message : sqsEvent.getRecords()) { 17 | try { 18 | //process your message 19 | } catch (Exception e) { 20 | //Add failed message identifier to the batchItemFailures list 21 | batchItemFailures.add(new SQSBatchResponse.BatchItemFailure(message.getMessageId())); 22 | } 23 | } 24 | return new SQSBatchResponse(batchItemFailures); 25 | } 26 | } -------------------------------------------------------------------------------- /lambda-function-sqs-report-batch-item-failures/example.mjs: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | // Node.js 20.x Lambda runtime, AWS SDK for Javascript V3 4 | export const handler = async (event, context) => { 5 | const batchItemFailures = []; 6 | for (const record of event.Records) { 7 | try { 8 | await processMessageAsync(record, context); 9 | } catch (error) { 10 | batchItemFailures.push({ itemIdentifier: record.messageId }); 11 | } 12 | } 13 | return { batchItemFailures }; 14 | }; 15 | 16 | async function processMessageAsync(record, context) { 17 | if (record.body && record.body.includes("error")) { 18 | throw new Error("There is an error in the SQS Message."); 19 | } 20 | console.log(`Processed message: ${record.body}`); 21 | } -------------------------------------------------------------------------------- /lambda-function-sqs-report-batch-item-failures/example.py: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: Apache-2.0 3 | 4 | def lambda_handler(event, context): 5 | if event: 6 | batch_item_failures = [] 7 | sqs_batch_response = {} 8 | 9 | for record in event["Records"]: 10 | try: 11 | # process message 12 | except Exception as e: 13 | batch_item_failures.append({"itemIdentifier": record['messageId']}) 14 | 15 | sqs_batch_response["batchItemFailures"] = batch_item_failures 16 | return sqs_batch_response -------------------------------------------------------------------------------- /lambda-function-sqs-report-batch-item-failures/example.rs: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | use aws_lambda_events::{ 4 | event::sqs::{SqsBatchResponse, SqsEvent}, 5 | sqs::{BatchItemFailure, SqsMessage}, 6 | }; 7 | use lambda_runtime::{run, service_fn, Error, LambdaEvent}; 8 | 9 | async fn process_record(_: &SqsMessage) -> Result<(), Error> { 10 | Err(Error::from("Error processing message")) 11 | } 12 | 13 | async fn function_handler(event: LambdaEvent) -> Result { 14 | let mut batch_item_failures = Vec::new(); 15 | for record in event.payload.records { 16 | match process_record(&record).await { 17 | Ok(_) => (), 18 | Err(_) => batch_item_failures.push(BatchItemFailure { 19 | item_identifier: record.message_id.unwrap(), 20 | }), 21 | } 22 | } 23 | 24 | Ok(SqsBatchResponse { 25 | batch_item_failures, 26 | }) 27 | } 28 | 29 | #[tokio::main] 30 | async fn main() -> Result<(), Error> { 31 | run(service_fn(function_handler)).await 32 | } 33 | -------------------------------------------------------------------------------- /lambda-function-sqs-report-batch-item-failures/example.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | import { SQSEvent, SQSBatchResponse, Context, SQSBatchItemFailure, SQSRecord } from 'aws-lambda'; 4 | 5 | export const handler = async (event: SQSEvent, context: Context): Promise => { 6 | const batchItemFailures: SQSBatchItemFailure[] = []; 7 | 8 | for (const record of event.Records) { 9 | try { 10 | await processMessageAsync(record); 11 | } catch (error) { 12 | batchItemFailures.push({ itemIdentifier: record.messageId }); 13 | } 14 | } 15 | 16 | return {batchItemFailures: batchItemFailures}; 17 | }; 18 | 19 | async function processMessageAsync(record: SQSRecord): Promise { 20 | if (record.body && record.body.includes("error")) { 21 | throw new Error('There is an error in the SQS Message.'); 22 | } 23 | console.log(`Processed message ${record.body}`); 24 | } 25 | -------------------------------------------------------------------------------- /lambda-function-throwing-errors/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /lambda-function-throwing-errors/snippet.txt: -------------------------------------------------------------------------------- 1 | exports.handler = async (event) => { 2 | const coinToss = Math.random()*100 3 | const failureRate = process.env.CHANCE_OF_FAILURE || 50 4 | 5 | console.log({coinToss, failureRate}) 6 | 7 | if ( coinToss < failureRate) { 8 | console.error('Error') 9 | throw Error("There was an error") 10 | } else { 11 | return { 12 | statusCode: 200, 13 | body: JSON.stringify('Hello from Lambda!'), 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /restrict-deployment-to-apigw-stage/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /restrict-deployment-to-apigw-stage/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "IAM Policy to restrict deployment to particular API stage", 3 | "description": "Using this policy a user access can be restricted to deploy API only to particular stage/s", 4 | "type": "Integration", 5 | "services": ["apigw", "iam"], 6 | "tags": [], 7 | "languages": ["json"], 8 | "introBox": { 9 | "headline": "How it works", 10 | "text": [ 11 | "The IAM policy allows deployment action only on the dev stage and not on other stages like prod" 12 | ] 13 | }, 14 | "gitHub": { 15 | "template": { 16 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/restrict-iamuser-deploy-to-apigw-stage agawanea" 17 | } 18 | }, 19 | "snippets": [ 20 | { 21 | "title": "Limit stage deployment to authorized user", 22 | "snippetPath": "snippet.txt", 23 | "language": "json" 24 | } 25 | ], 26 | "authors": [ 27 | { 28 | "headline": "Presented by Abhishek Agawane", 29 | "name": "Abhishek Agawane", 30 | "image": "https://drive.google.com/file/d/1E-5koDaKEaMUtOctX32I9TLwfh3kgpAq/view?usp=drivesdk", 31 | "bio": "Abhishek Agawane is a Cloud Support Engineer at AWS who focuses on serverless and is passionate about Cloud", 32 | "linkedin": "https://www.linkedin.com/in/agawabhi/" 33 | } 34 | ] 35 | } 36 | -------------------------------------------------------------------------------- /restrict-deployment-to-apigw-stage/snippet.txt: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Sid": "VisualEditor0", 6 | "Effect": "Allow", 7 | "Action": "apigateway:POST", 8 | "Resource": [ 9 | "arn:aws:apigateway:us-east-1::/restapis//deployments" 10 | ], 11 | "Condition": { 12 | "ForAnyValue:StringEquals": { 13 | "apigateway:Request/StageName": "dev" 14 | } 15 | } 16 | } 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /scripts/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "scripts", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "validate.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "@octokit/rest": "^19.0.4", 14 | "jsonschema": "^1.4.1", 15 | "node-fetch": "^2.7.0" 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /scripts/snippet.txt: -------------------------------------------------------------------------------- 1 | filter @type = "REPORT" 2 | | stats max(@memorySize / 1000 / 1000) as provisonedMemoryMB, 3 | min(@maxMemoryUsed / 1000 / 1024) as smallestMemoryRequestMB, 4 | avg(@maxMemoryUsed / 1024 / 1024) as avgMemoryUsedMB, 5 | max(@maxMemoryUsed / 1024 / 1024) as maxMemoryUsedMB, 6 | provisonedMemoryMB - maxMemoryUsedMB as overProvisionedMB -------------------------------------------------------------------------------- /scripts/template/README.md: -------------------------------------------------------------------------------- 1 | # Running the CloudWatch Logs Insight Snippet 2 | 3 | [[description]] 4 | 5 | Learn more about this snippet at Serverless Land Snippets: https://serverlessland.com/snippets/[[folder-name]] 6 | 7 | Important: this application could use various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example. 8 | 9 | 10 | ## How it works 11 | 12 | Uses CloudWatch Insights to query a given log group and returns the number of execptions for a given log group. 13 | 14 | [Follow the instructions on the snippet page](https://serverlessland.com/snippets/[[folder-name]]) to run in your AWS account. 15 | 16 | 17 | ## Cleanup 18 | 19 | No clean up required. 20 | 21 | --- 22 | 23 | Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. 24 | 25 | SPDX-License-Identifier: MIT-0 26 | -------------------------------------------------------------------------------- /scripts/template/snippet-data.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "[[title]]", 3 | "description": "[[description]]", 4 | "type": "CloudWatch Logs Insights", 5 | "services": ["[[services]]"], 6 | "introBox": { 7 | "headline": "How it works", 8 | "text": ["[[detail]]"] 9 | }, 10 | "gitHub": { 11 | "template": { 12 | "repoURL": "https://github.com/aws-samples/serverless-snippets/tree/main/[[snippet]]", 13 | "snippetDir": "/", 14 | "snippetFile": "snippet.txt", 15 | "snippetLanguage": "" 16 | } 17 | }, 18 | "authors": [ 19 | { 20 | "headline": "Presented by David Boyne", 21 | "name": "David Boyne", 22 | "image": "https://pbs.twimg.com/profile_images/1262283153563140096/DYRDqKg6_400x400.png", 23 | "bio": "Serverless Developer Advocate at AWS", 24 | "linkedin": "", 25 | "twitter": "boyney123" 26 | } 27 | ] 28 | } 29 | -------------------------------------------------------------------------------- /serverlessland.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/serverless-snippets/HEAD/serverlessland.png -------------------------------------------------------------------------------- /snippets.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/serverless-snippets/HEAD/snippets.png -------------------------------------------------------------------------------- /stepfunctions-intrinsic-function-getYYMMfromContext/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /stepfunctions-intrinsic-function-getYYMMfromContext/snippet.txt: -------------------------------------------------------------------------------- 1 | { 2 | "StartAt": "SimpleTask", 3 | "States": { 4 | "SimpleTask": { 5 | "Type": "Task", 6 | "Resource": "arn:aws:states:::dynamodb:putItem", 7 | "Parameters": { 8 | "TableName": "${TableName}", 9 | "Item": { 10 | "YYMM": { 11 | "S.$": "States.Format('{}{}', States.ArrayGetItem(States.StringSplit(States.ArrayGetItem(States.StringSplit($$.State.EnteredTime, 'T'), 0), '-'), 0),States.ArrayGetItem(States.StringSplit(States.ArrayGetItem(States.StringSplit($$.State.EnteredTime, 'T'), 0), '-'), 1))" 12 | }, 13 | "id": { 14 | "S.$": "$$.State.EnteredTime" 15 | } 16 | } 17 | }, 18 | "End": true 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /tools-powertools-logger/Function.cs: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | using Amazon.Lambda.Core; 4 | using AWS.Lambda.Powertools.Logging; 5 | 6 | [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] 7 | 8 | namespace Powertools.Logging 9 | { 10 | public class Function 11 | { 12 | // Powertools Logger requires an environment variables against your function 13 | // POWERTOOLS_SERVICE_NAME 14 | [Logging(LogEvent = true)] 15 | public void Handler(object request, ILambdaContext context) 16 | { 17 | try 18 | { 19 | var requestContextRequestId = Guid.NewGuid().ToString(); 20 | 21 | var lookupInfo = new Dictionary() 22 | { 23 | {"LookupInfo", new Dictionary{{ "LookupId", requestContextRequestId }}} 24 | }; 25 | 26 | // Append custom keys to the structured logs 27 | Logger.AppendKeys(lookupInfo); 28 | 29 | Logger.LogInformation("Getting ip address from external service"); 30 | } 31 | catch (Exception ex) 32 | { 33 | Logger.LogError(ex, "Failure processing request"); 34 | } 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /tools-powertools-logger/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /tools-powertools-logger/powertools-logger.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | import { Logger, injectLambdaContext } from '@aws-lambda-powertools/logger'; 4 | import middy from '@middy/core'; 5 | 6 | const logger = new Logger({ 7 | logLevel: 'INFO', 8 | serviceName: 'shopping-cart-api', 9 | }); 10 | 11 | const lambdaHandler = async (): Promise => { 12 | logger.info('This is an INFO log with some context'); 13 | }; 14 | 15 | export const handler = middy(lambdaHandler).use(injectLambdaContext(logger)); 16 | -------------------------------------------------------------------------------- /tools-powertools-metrics/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /tools-powertools-metrics/powertools-metrics.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | import { Metrics } from '@aws-lambda-powertools/metrics'; 4 | 5 | const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' }); 6 | 7 | export const handler = async (_event, _context): Promise => { 8 | // ... 9 | }; -------------------------------------------------------------------------------- /tools-powertools-tracing/Function.cs: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | using Amazon.Lambda.Core; 4 | using AWS.Lambda.Powertools.Tracing; 5 | 6 | [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] 7 | 8 | namespace Powertools.Trace 9 | { 10 | public class Function 11 | { 12 | // Powertools Logger requires an environment variables against your function 13 | // POWERTOOLS_SERVICE_NAME 14 | 15 | [Tracing] 16 | public void Handler(object request, ILambdaContext context) 17 | { 18 | Tracing.AddAnnotation("annotation", "value"); 19 | Tracing.AddMetadata("metadata", "sample"); 20 | 21 | Tracing.WithSubsegment("loggingResponse", (subsegment) => { 22 | // Some business logic 23 | }); 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /tools-powertools-tracing/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /vpc-subnets-serverless/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Explore ServerlessLand

4 | 5 | 6 | ![ServerlessLand.com](../serverlessland.png) 7 | [Explore 700+ patterns](https://serverlessland.com/patterns?ref=github-snippets) | [Explore 50+ guides](https://serverlessland.com/learn?ref=github-snippets) | [Explore 80+ guides](https://serverlessland.com/snippets?ref=github-snippets) 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /vpc-subnets-serverless/snippet.txt: -------------------------------------------------------------------------------- 1 | for region in `aws ec2 describe-regions --query "Regions[].RegionName" --region us-east-1 --output text` 2 | do 3 | echo "[${region}]" 4 | aws ec2 describe-subnets --filters "Name=tag:VPCname,Values=HappyVPC" --query "Subnets[*].SubnetId" --output text --region ${region} 5 | done 6 | echo "finished" 7 | --------------------------------------------------------------------------------