diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..5509140f --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*.DS_Store diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..c5f3f6b9 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "java.configuration.updateBuildConfiguration": "interactive" +} \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index bfeb4d27..2bc36383 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,56 +1,64 @@ -# Guidelines for contributing +# Contributing Guidelines -Thank you for your interest in contributing to AWS documentation! We greatly value feedback and contributions from our community. +Thank you for your interest in contributing to our project. We greatly value feedback and contributions from our community. -Please read through this document before you submit any pull requests or issues. It will help us work together more effectively. +Please read through this document before submitting any issues or pull requests to ensure we have all the necessary +information to effectively respond to your bug report or contribution. -## What to expect when you contribute -When you submit a pull request, our team is notified and will respond as quickly as we can. We'll do our best to work with you to ensure that your pull request adheres to our style and standards. If we merge your pull request, we might make additional edits later for style or clarity. +## Reporting Bugs/Feature Requests -The AWS documentation source files on GitHub aren't published directly to the official documentation website. If we merge your pull request, we'll publish your changes to the documentation website as soon as we can, but they won't appear immediately or automatically. +We welcome you to use the GitHub issue tracker to report bugs or suggest features. -We look forward to receiving your pull requests for: +When filing an issue, please check existing open, or recently closed, issues to make sure somebody else hasn't already +reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: -* New content you'd like to contribute (such as new code samples or tutorials) -* Inaccuracies in the content -* Information gaps in the content that need more detail to be complete -* Typos or grammatical errors -* Suggested rewrites that improve clarity and reduce confusion +* A reproducible test case or series of steps +* The version of our code being used +* Any modifications you've made relevant to the bug +* Anything unusual about your environment or deployment -**Note:** We all write differently, and you might not like how we've written or organized something currently. We want that feedback. But please be sure that your request for a rewrite is supported by the previous criteria. If it isn't, we might decline to merge it. -## How to contribute +## Contributing via Pull Requests -To contribute, send us a pull request. For small changes, such as fixing a typo or adding a link, you can use the [GitHub Edit Button](https://blog.github.com/2011-04-26-forking-with-the-edit-button/). For larger changes: +Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: -1. [Fork the repository](https://help.github.com/articles/fork-a-repo/). -2. In your fork, make your change in a branch that's based on this repo's **master** branch. -3. Commit the change to your fork, using a clear and descriptive commit message. -4. [Create a pull request](https://help.github.com/articles/creating-a-pull-request-from-a-fork/), answering any questions in the pull request form. +1. You are working against the latest source on the *main* branch. +2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. +3. You open an issue to discuss any significant work - we would hate for your time to be wasted. -Before you send us a pull request, please be sure that: +To send us a pull request, please: -1. You're working from the latest source on the **master** branch. -2. You check [existing open](https://github.com/awsdocs/aws-lambda-developer-guide/pulls), and [recently closed](https://github.com/awsdocs/aws-lambda-developer-guide/pulls?q=is%3Apr+is%3Aclosed), pull requests to be sure that someone else hasn't already addressed the problem. -3. You [create an issue](https://github.com/awsdocs/aws-lambda-developer-guide/issues/new) before working on a contribution that will take a significant amount of your time. +1. Fork the repository. +2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. +3. Ensure local tests pass. +4. Commit to your fork using clear commit messages. +5. Send us a pull request, answering any default questions in the pull request interface. +6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. + +GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and +[creating a pull request](https://help.github.com/articles/creating-a-pull-request/). -For contributions that will take a significant amount of time, [open a new issue](https://github.com/awsdocs/aws-lambda-developer-guide/issues/new) to pitch your idea before you get started. Explain the problem and describe the content you want to see added to the documentation. Let us know if you'll write it yourself or if you'd like us to help. We'll discuss your proposal with you and let you know whether we're likely to accept it. We don't want you to spend a lot of time on a contribution that might be outside the scope of the documentation or that's already in the works. ## Finding contributions to work on -If you'd like to contribute, but don't have a project in mind, look at the [open issues](https://github.com/awsdocs/aws-lambda-developer-guide/issues) in this repository for some ideas. Any issues with the [help wanted](https://github.com/awsdocs/aws-lambda-developer-guide/labels/help%20wanted) or [enhancement](https://github.com/awsdocs/aws-lambda-developer-guide/labels/enhancement) labels are a great place to start. +Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any 'help wanted' issues is a great place to start. + -In addition to written content, we really appreciate new examples and code samples for our documentation, such as examples for different platforms or environments, and code samples in additional languages. +## Code of Conduct -## Code of conduct +This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). +For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact +opensource-codeofconduct@amazon.com with any additional questions or comments. -This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). For more information, see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact [opensource-codeofconduct@amazon.com](mailto:opensource-codeofconduct@amazon.com) with any additional questions or comments. ## Security issue notifications -If you discover a potential security issue, please notify AWS Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public issue on GitHub. +If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. + ## Licensing -See the [LICENSE](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/LICENSE) file for this project's licensing. We will ask you to confirm the licensing of your contribution. We may ask you to sign a [Contributor License Agreement (CLA)](http://en.wikipedia.org/wiki/Contributor_License_Agreement) for larger changes. +See the [LICENSE](LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. + +We may ask you to sign a [Contributor License Agreement (CLA)](http://en.wikipedia.org/wiki/Contributor_License_Agreement) for larger changes. diff --git a/LICENSE b/LICENSE index 7785b904..6aa0c458 100644 --- a/LICENSE +++ b/LICENSE @@ -1,152 +1,14 @@ -Creative Commons Attribution-ShareAlike 4.0 International Public License - -By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. - -Section 1 – Definitions. - - a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. - - b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. - - c. BY-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License. - - d. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. - - e. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. - - f. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. - - g. License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution and ShareAlike. - - h. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. - - i. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. - - j. Licensor means the individual(s) or entity(ies) granting rights under this Public License. - - k. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. - - l. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. - - m. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. - -Section 2 – Scope. - - a. License grant. - - 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: - - A. reproduce and Share the Licensed Material, in whole or in part; and - - B. produce, reproduce, and Share Adapted Material. - - 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. - - 3. Term. The term of this Public License is specified in Section 6(a). - - 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. - - 5. Downstream recipients. - - A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. - - B. Additional offer from the Licensor – Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter’s License You apply. - - C. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. - - 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). - - b. Other rights. - - 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. - - 2. Patent and trademark rights are not licensed under this Public License. - - 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties. - -Section 3 – License Conditions. - -Your exercise of the Licensed Rights is expressly made subject to the following conditions. - - a. Attribution. - - 1. If You Share the Licensed Material (including in modified form), You must: - - A. retain the following if it is supplied by the Licensor with the Licensed Material: - - i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); - - ii. a copyright notice; - - iii. a notice that refers to this Public License; - - iv. a notice that refers to the disclaimer of warranties; - - v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; - - B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and - - C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. - - 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. - - 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. - - b. ShareAlike.In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply. - - 1. The Adapter’s License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-SA Compatible License. - - 2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material. - - 3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply. - -Section 4 – Sui Generis Database Rights. - -Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: - - a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database; - - b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and - - c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. -For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. - -Section 5 – Disclaimer of Warranties and Limitation of Liability. - - a. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You. - - b. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You. - - c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. - -Section 6 – Term and Termination. - - a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. - - b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: - - 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or - - 2. upon express reinstatement by the Licensor. - - c. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. - - d. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. - - e. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. - -Section 7 – Other Terms and Conditions. - - a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. - - b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. - -Section 8 – Interpretation. - - a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. - - b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. - - c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. - - d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/LICENSE-SAMPLECODE b/LICENSE-SAMPLECODE deleted file mode 100644 index 7e0bd89d..00000000 --- a/LICENSE-SAMPLECODE +++ /dev/null @@ -1,14 +0,0 @@ -Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy of this -software and associated documentation files (the "Software"), to deal in the Software -without restriction, including without limitation the rights to use, copy, modify, -merge, publish, distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/LICENSE-SUMMARY b/LICENSE-SUMMARY deleted file mode 100644 index fa2e5700..00000000 --- a/LICENSE-SUMMARY +++ /dev/null @@ -1,5 +0,0 @@ -Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -The documentation is made available under the Creative Commons Attribution-ShareAlike 4.0 International License. See the LICENSE file. - -The sample code within this documentation is made available under a modified MIT license. See the LICENSE-SAMPLECODE file. diff --git a/README.md b/README.md index 4d307c17..edefa865 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,11 @@ ## AWS Lambda Developer Guide -This repository contains the Markdown version of the AWS Lambda Developer Guide and sample applications that you can deploy to learn about Lambda concepts and features. +This repository contains additional resources for the AWS Lambda developer guide. -Table of contents: [index.md](/doc_source/index.md) +- [iam-policies](./iam-policies) - Sample permissions policies for cross-service use cases. +- [sample-apps](./sample-apps) - Sample applications that demonstrate features and use cases for the AWS Lambda service and managed runtimes. +- [templates](./templates) - AWS CloudFormation templates for creating functions and VPC network resources. ## License Summary -The documentation is made available under the Creative Commons Attribution-ShareAlike 4.0 International License. See the [LICENSE](./LICENSE) file. - -The sample code within this documentation is made available under a modified MIT license. See the [LICENSE-SAMPLECODE](./LICENSE-SAMPLECODE) file. +The sample code within this repo is made available under a modified MIT license. See the [LICENSE](./LICENSE) file. diff --git a/doc_source/API_AccountLimit.md b/doc_source/API_AccountLimit.md deleted file mode 100644 index 5f40217b..00000000 --- a/doc_source/API_AccountLimit.md +++ /dev/null @@ -1,39 +0,0 @@ -# AccountLimit - -Limits that are related to concurrency and storage\. All file and storage sizes are in bytes\. - -## Contents - - **CodeSizeUnzipped** -The maximum size of a function's deployment package and layers when they're extracted\. -Type: Long -Required: No - - **CodeSizeZipped** -The maximum size of a deployment package when it's uploaded directly to AWS Lambda\. Use Amazon S3 for larger files\. -Type: Long -Required: No - - **ConcurrentExecutions** -The maximum number of simultaneous function executions\. -Type: Integer -Required: No - - **TotalCodeSize** -The amount of storage space that you can use for all deployment packages and layer archives\. -Type: Long -Required: No - - **UnreservedConcurrentExecutions** -The maximum number of simultaneous function executions, minus the capacity that's reserved for individual functions with [PutFunctionConcurrency](API_PutFunctionConcurrency.md)\. -Type: Integer -Valid Range: Minimum value of 0\. -Required: No - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/AccountLimit) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/AccountLimit) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/AccountLimit) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/AccountLimit) \ No newline at end of file diff --git a/doc_source/API_AccountUsage.md b/doc_source/API_AccountUsage.md deleted file mode 100644 index 5ca7c5ad..00000000 --- a/doc_source/API_AccountUsage.md +++ /dev/null @@ -1,23 +0,0 @@ -# AccountUsage - -The number of functions and amount of storage in use\. - -## Contents - - **FunctionCount** -The number of Lambda functions\. -Type: Long -Required: No - - **TotalCodeSize** -The amount of storage space, in bytes, that's being used by deployment packages and layer archives\. -Type: Long -Required: No - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/AccountUsage) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/AccountUsage) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/AccountUsage) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/AccountUsage) \ No newline at end of file diff --git a/doc_source/API_AddLayerVersionPermission.md b/doc_source/API_AddLayerVersionPermission.md deleted file mode 100644 index 7c4c2bf9..00000000 --- a/doc_source/API_AddLayerVersionPermission.md +++ /dev/null @@ -1,132 +0,0 @@ -# AddLayerVersionPermission - -Adds permissions to the resource\-based policy of a version of an [AWS Lambda layer](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)\. Use this action to grant layer usage permission to other accounts\. You can grant permission to a single account, all AWS accounts, or all accounts in an organization\. - -To revoke permission, call [RemoveLayerVersionPermission](API_RemoveLayerVersionPermission.md) with the statement ID that you specified when you added it\. - -## Request Syntax - -``` -POST /2018-10-31/layers/LayerName/versions/VersionNumber/policy?RevisionId=RevisionId HTTP/1.1 -Content-type: application/json - -{ - "[Action](#SSS-AddLayerVersionPermission-request-Action)": "string", - "[OrganizationId](#SSS-AddLayerVersionPermission-request-OrganizationId)": "string", - "[Principal](#SSS-AddLayerVersionPermission-request-Principal)": "string", - "[StatementId](#SSS-AddLayerVersionPermission-request-StatementId)": "string" -} -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [LayerName](#API_AddLayerVersionPermission_RequestSyntax) ** -The name or Amazon Resource Name \(ARN\) of the layer\. -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:[a-zA-Z0-9-]+:lambda:[a-zA-Z0-9-]+:\d{12}:layer:[a-zA-Z0-9-_]+)|[a-zA-Z0-9-_]+` - - ** [RevisionId](#API_AddLayerVersionPermission_RequestSyntax) ** -Only update the policy if the revision ID matches the ID specified\. Use this option to avoid modifying a policy that has changed since you last read it\. - - ** [VersionNumber](#API_AddLayerVersionPermission_RequestSyntax) ** -The version number\. - -## Request Body - -The request accepts the following data in JSON format\. - - ** [Action](#API_AddLayerVersionPermission_RequestSyntax) ** -The API action that grants access to the layer\. For example, `lambda:GetLayerVersion`\. -Type: String -Pattern: `lambda:GetLayerVersion` -Required: Yes - - ** [OrganizationId](#API_AddLayerVersionPermission_RequestSyntax) ** -With the principal set to `*`, grant permission to all accounts in the specified organization\. -Type: String -Pattern: `o-[a-z0-9]{10,32}` -Required: No - - ** [Principal](#API_AddLayerVersionPermission_RequestSyntax) ** -An account ID, or `*` to grant permission to all AWS accounts\. -Type: String -Pattern: `\d{12}|\*|arn:(aws[a-zA-Z-]*):iam::\d{12}:root` -Required: Yes - - ** [StatementId](#API_AddLayerVersionPermission_RequestSyntax) ** -An identifier that distinguishes the policy from others on the same layer version\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 100\. -Pattern: `([a-zA-Z0-9-_]+)` -Required: Yes - -## Response Syntax - -``` -HTTP/1.1 201 -Content-type: application/json - -{ - "[RevisionId](#SSS-AddLayerVersionPermission-response-RevisionId)": "string", - "[Statement](#SSS-AddLayerVersionPermission-response-Statement)": "string" -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 201 response\. - -The following data is returned in JSON format by the service\. - - ** [RevisionId](#API_AddLayerVersionPermission_ResponseSyntax) ** -A unique identifier for the current revision of the policy\. -Type: String - - ** [Statement](#API_AddLayerVersionPermission_ResponseSyntax) ** -The permission statement\. -Type: String - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **PolicyLengthExceededException** -The permissions policy for the resource is too large\. [Learn more](https://docs.aws.amazon.com/lambda/latest/dg/limits.html) -HTTP Status Code: 400 - - **PreconditionFailedException** -The RevisionId provided does not match the latest RevisionId for the Lambda function or alias\. Call the `GetFunction` or the `GetAlias` API to retrieve the latest RevisionId for your resource\. -HTTP Status Code: 412 - - **ResourceConflictException** -The resource already exists, or another operation is in progress\. -HTTP Status Code: 409 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/AddLayerVersionPermission) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/AddLayerVersionPermission) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/AddLayerVersionPermission) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/AddLayerVersionPermission) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/AddLayerVersionPermission) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/AddLayerVersionPermission) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/AddLayerVersionPermission) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/AddLayerVersionPermission) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/AddLayerVersionPermission) \ No newline at end of file diff --git a/doc_source/API_AddPermission.md b/doc_source/API_AddPermission.md deleted file mode 100644 index b041fdbc..00000000 --- a/doc_source/API_AddPermission.md +++ /dev/null @@ -1,155 +0,0 @@ -# AddPermission - -Grants an AWS service or another account permission to use a function\. You can apply the policy at the function level, or specify a qualifier to restrict access to a single version or alias\. If you use a qualifier, the invoker must use the full Amazon Resource Name \(ARN\) of that version or alias to invoke the function\. - -To grant permission to another account, specify the account ID as the `Principal`\. For AWS services, the principal is a domain\-style identifier defined by the service, like `s3.amazonaws.com` or `sns.amazonaws.com`\. For AWS services, you can also specify the ARN of the associated resource as the `SourceArn`\. If you grant permission to a service principal without specifying the source, other accounts could potentially configure resources in their account to invoke your Lambda function\. - -This action adds a statement to a resource\-based permissions policy for the function\. For more information about function policies, see [Lambda Function Policies](https://docs.aws.amazon.com/lambda/latest/dg/access-control-resource-based.html)\. - -## Request Syntax - -``` -POST /2015-03-31/functions/FunctionName/policy?Qualifier=Qualifier HTTP/1.1 -Content-type: application/json - -{ - "[Action](#SSS-AddPermission-request-Action)": "string", - "[EventSourceToken](#SSS-AddPermission-request-EventSourceToken)": "string", - "[Principal](#SSS-AddPermission-request-Principal)": "string", - "[RevisionId](#SSS-AddPermission-request-RevisionId)": "string", - "[SourceAccount](#SSS-AddPermission-request-SourceAccount)": "string", - "[SourceArn](#SSS-AddPermission-request-SourceArn)": "string", - "[StatementId](#SSS-AddPermission-request-StatementId)": "string" -} -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [FunctionName](#API_AddPermission_RequestSyntax) ** -The name of the Lambda function, version, or alias\. - -**Name formats** -+ **Function name** \- `my-function` \(name\-only\), `my-function:v1` \(with alias\)\. -+ **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:my-function`\. -+ **Partial ARN** \- `123456789012:function:my-function`\. -You can append a version number or alias to any of the formats\. The length constraint applies only to the full ARN\. If you specify only the function name, it is limited to 64 characters in length\. -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [Qualifier](#API_AddPermission_RequestSyntax) ** -Specify a version or alias to add permissions to a published version of the function\. -Length Constraints: Minimum length of 1\. Maximum length of 128\. -Pattern: `(|[a-zA-Z0-9$_-]+)` - -## Request Body - -The request accepts the following data in JSON format\. - - ** [Action](#API_AddPermission_RequestSyntax) ** -The action that the principal can use on the function\. For example, `lambda:InvokeFunction` or `lambda:GetFunction`\. -Type: String -Pattern: `(lambda:[*]|lambda:[a-zA-Z]+|[*])` -Required: Yes - - ** [EventSourceToken](#API_AddPermission_RequestSyntax) ** -For Alexa Smart Home functions, a token that must be supplied by the invoker\. -Type: String -Length Constraints: Minimum length of 0\. Maximum length of 256\. -Pattern: `[a-zA-Z0-9._\-]+` -Required: No - - ** [Principal](#API_AddPermission_RequestSyntax) ** -The AWS service or account that invokes the function\. If you specify a service, use `SourceArn` or `SourceAccount` to limit who can invoke the function through that service\. -Type: String -Pattern: `.*` -Required: Yes - - ** [RevisionId](#API_AddPermission_RequestSyntax) ** -Only update the policy if the revision ID matches the ID that's specified\. Use this option to avoid modifying a policy that has changed since you last read it\. -Type: String -Required: No - - ** [SourceAccount](#API_AddPermission_RequestSyntax) ** -For Amazon S3, the ID of the account that owns the resource\. Use this together with `SourceArn` to ensure that the resource is owned by the specified account\. It is possible for an Amazon S3 bucket to be deleted by its owner and recreated by another account\. -Type: String -Pattern: `\d{12}` -Required: No - - ** [SourceArn](#API_AddPermission_RequestSyntax) ** -For AWS services, the ARN of the AWS resource that invokes the function\. For example, an Amazon S3 bucket or Amazon SNS topic\. -Type: String -Pattern: `arn:(aws[a-zA-Z0-9-]*):([a-zA-Z0-9\-])+:([a-z]{2}(-gov)?-[a-z]+-\d{1})?:(\d{12})?:(.*)` -Required: No - - ** [StatementId](#API_AddPermission_RequestSyntax) ** -A statement identifier that differentiates the statement from others in the same policy\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 100\. -Pattern: `([a-zA-Z0-9-_]+)` -Required: Yes - -## Response Syntax - -``` -HTTP/1.1 201 -Content-type: application/json - -{ - "[Statement](#SSS-AddPermission-response-Statement)": "string" -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 201 response\. - -The following data is returned in JSON format by the service\. - - ** [Statement](#API_AddPermission_ResponseSyntax) ** -The permission statement that's added to the function policy\. -Type: String - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **PolicyLengthExceededException** -The permissions policy for the resource is too large\. [Learn more](https://docs.aws.amazon.com/lambda/latest/dg/limits.html) -HTTP Status Code: 400 - - **PreconditionFailedException** -The RevisionId provided does not match the latest RevisionId for the Lambda function or alias\. Call the `GetFunction` or the `GetAlias` API to retrieve the latest RevisionId for your resource\. -HTTP Status Code: 412 - - **ResourceConflictException** -The resource already exists, or another operation is in progress\. -HTTP Status Code: 409 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/AddPermission) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/AddPermission) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/AddPermission) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/AddPermission) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/AddPermission) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/AddPermission) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/AddPermission) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/AddPermission) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/AddPermission) \ No newline at end of file diff --git a/doc_source/API_AliasConfiguration.md b/doc_source/API_AliasConfiguration.md deleted file mode 100644 index c4850463..00000000 --- a/doc_source/API_AliasConfiguration.md +++ /dev/null @@ -1,49 +0,0 @@ -# AliasConfiguration - -Provides configuration information about a Lambda function [alias](https://docs.aws.amazon.com/lambda/latest/dg/versioning-aliases.html)\. - -## Contents - - **AliasArn** -The Amazon Resource Name \(ARN\) of the alias\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}(-gov)?-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?` -Required: No - - **Description** -A description of the alias\. -Type: String -Length Constraints: Minimum length of 0\. Maximum length of 256\. -Required: No - - **FunctionVersion** -The function version that the alias invokes\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 1024\. -Pattern: `(\$LATEST|[0-9]+)` -Required: No - - **Name** -The name of the alias\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 128\. -Pattern: `(?!^[0-9]+$)([a-zA-Z0-9-_]+)` -Required: No - - **RevisionId** -A unique identifier that changes when you update the alias\. -Type: String -Required: No - - **RoutingConfig** -The [routing configuration](https://docs.aws.amazon.com/lambda/latest/dg/lambda-traffic-shifting-using-aliases.html) of the alias\. -Type: [AliasRoutingConfiguration](API_AliasRoutingConfiguration.md) object -Required: No - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/AliasConfiguration) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/AliasConfiguration) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/AliasConfiguration) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/AliasConfiguration) \ No newline at end of file diff --git a/doc_source/API_AliasRoutingConfiguration.md b/doc_source/API_AliasRoutingConfiguration.md deleted file mode 100644 index 9ff6423c..00000000 --- a/doc_source/API_AliasRoutingConfiguration.md +++ /dev/null @@ -1,21 +0,0 @@ -# AliasRoutingConfiguration - -The [traffic\-shifting](https://docs.aws.amazon.com/lambda/latest/dg/lambda-traffic-shifting-using-aliases.html) configuration of a Lambda function alias\. - -## Contents - - **AdditionalVersionWeights** -The name of the second alias, and the percentage of traffic that's routed to it\. -Type: String to double map -Key Length Constraints: Minimum length of 1\. Maximum length of 1024\. -Key Pattern: `[0-9]+` -Valid Range: Minimum value of 0\.0\. Maximum value of 1\.0\. -Required: No - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/AliasRoutingConfiguration) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/AliasRoutingConfiguration) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/AliasRoutingConfiguration) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/AliasRoutingConfiguration) \ No newline at end of file diff --git a/doc_source/API_Concurrency.md b/doc_source/API_Concurrency.md deleted file mode 100644 index 68753c1d..00000000 --- a/doc_source/API_Concurrency.md +++ /dev/null @@ -1,17 +0,0 @@ -# Concurrency - -## Contents - - **ReservedConcurrentExecutions** -The number of concurrent executions that are reserved for this function\. For more information, see [Managing Concurrency](https://docs.aws.amazon.com/lambda/latest/dg/concurrent-executions.html)\. -Type: Integer -Valid Range: Minimum value of 0\. -Required: No - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/Concurrency) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/Concurrency) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/Concurrency) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/Concurrency) \ No newline at end of file diff --git a/doc_source/API_CreateAlias.md b/doc_source/API_CreateAlias.md deleted file mode 100644 index 6c824d66..00000000 --- a/doc_source/API_CreateAlias.md +++ /dev/null @@ -1,158 +0,0 @@ -# CreateAlias - -Creates an [alias](https://docs.aws.amazon.com/lambda/latest/dg/versioning-aliases.html) for a Lambda function version\. Use aliases to provide clients with a function identifier that you can update to invoke a different version\. - -You can also map an alias to split invocation requests between two versions\. Use the `RoutingConfig` parameter to specify a second version and the percentage of invocation requests that it receives\. - -## Request Syntax - -``` -POST /2015-03-31/functions/FunctionName/aliases HTTP/1.1 -Content-type: application/json - -{ - "[Description](#SSS-CreateAlias-request-Description)": "string", - "[FunctionVersion](#SSS-CreateAlias-request-FunctionVersion)": "string", - "[Name](#SSS-CreateAlias-request-Name)": "string", - "[RoutingConfig](#SSS-CreateAlias-request-RoutingConfig)": { - "[AdditionalVersionWeights](API_AliasRoutingConfiguration.md#SSS-Type-AliasRoutingConfiguration-AdditionalVersionWeights)": { - "string" : number - } - } -} -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [FunctionName](#API_CreateAlias_RequestSyntax) ** -The name of the Lambda function\. - -**Name formats** -+ **Function name** \- `MyFunction`\. -+ **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:MyFunction`\. -+ **Partial ARN** \- `123456789012:function:MyFunction`\. -The length constraint applies only to the full ARN\. If you specify only the function name, it is limited to 64 characters in length\. -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - -## Request Body - -The request accepts the following data in JSON format\. - - ** [Description](#API_CreateAlias_RequestSyntax) ** -A description of the alias\. -Type: String -Length Constraints: Minimum length of 0\. Maximum length of 256\. -Required: No - - ** [FunctionVersion](#API_CreateAlias_RequestSyntax) ** -The function version that the alias invokes\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 1024\. -Pattern: `(\$LATEST|[0-9]+)` -Required: Yes - - ** [Name](#API_CreateAlias_RequestSyntax) ** -The name of the alias\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 128\. -Pattern: `(?!^[0-9]+$)([a-zA-Z0-9-_]+)` -Required: Yes - - ** [RoutingConfig](#API_CreateAlias_RequestSyntax) ** -The [routing configuration](https://docs.aws.amazon.com/lambda/latest/dg/lambda-traffic-shifting-using-aliases.html) of the alias\. -Type: [AliasRoutingConfiguration](API_AliasRoutingConfiguration.md) object -Required: No - -## Response Syntax - -``` -HTTP/1.1 201 -Content-type: application/json - -{ - "[AliasArn](#SSS-CreateAlias-response-AliasArn)": "string", - "[Description](#SSS-CreateAlias-response-Description)": "string", - "[FunctionVersion](#SSS-CreateAlias-response-FunctionVersion)": "string", - "[Name](#SSS-CreateAlias-response-Name)": "string", - "[RevisionId](#SSS-CreateAlias-response-RevisionId)": "string", - "[RoutingConfig](#SSS-CreateAlias-response-RoutingConfig)": { - "[AdditionalVersionWeights](API_AliasRoutingConfiguration.md#SSS-Type-AliasRoutingConfiguration-AdditionalVersionWeights)": { - "string" : number - } - } -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 201 response\. - -The following data is returned in JSON format by the service\. - - ** [AliasArn](#API_CreateAlias_ResponseSyntax) ** -The Amazon Resource Name \(ARN\) of the alias\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}(-gov)?-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [Description](#API_CreateAlias_ResponseSyntax) ** -A description of the alias\. -Type: String -Length Constraints: Minimum length of 0\. Maximum length of 256\. - - ** [FunctionVersion](#API_CreateAlias_ResponseSyntax) ** -The function version that the alias invokes\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 1024\. -Pattern: `(\$LATEST|[0-9]+)` - - ** [Name](#API_CreateAlias_ResponseSyntax) ** -The name of the alias\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 128\. -Pattern: `(?!^[0-9]+$)([a-zA-Z0-9-_]+)` - - ** [RevisionId](#API_CreateAlias_ResponseSyntax) ** -A unique identifier that changes when you update the alias\. -Type: String - - ** [RoutingConfig](#API_CreateAlias_ResponseSyntax) ** -The [routing configuration](https://docs.aws.amazon.com/lambda/latest/dg/lambda-traffic-shifting-using-aliases.html) of the alias\. -Type: [AliasRoutingConfiguration](API_AliasRoutingConfiguration.md) object - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceConflictException** -The resource already exists, or another operation is in progress\. -HTTP Status Code: 409 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/CreateAlias) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/CreateAlias) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/CreateAlias) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/CreateAlias) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/CreateAlias) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/CreateAlias) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/CreateAlias) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/CreateAlias) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/CreateAlias) \ No newline at end of file diff --git a/doc_source/API_CreateEventSourceMapping.md b/doc_source/API_CreateEventSourceMapping.md deleted file mode 100644 index 4a1021e7..00000000 --- a/doc_source/API_CreateEventSourceMapping.md +++ /dev/null @@ -1,269 +0,0 @@ -# CreateEventSourceMapping - -Creates a mapping between an event source and an AWS Lambda function\. Lambda reads items from the event source and triggers the function\. - -For details about each event source type, see the following topics\. -+ [Using AWS Lambda with Amazon DynamoDB](https://docs.aws.amazon.com/lambda/latest/dg/with-ddb.html) -+ [Using AWS Lambda with Amazon Kinesis](https://docs.aws.amazon.com/lambda/latest/dg/with-kinesis.html) -+ [Using AWS Lambda with Amazon SQS](https://docs.aws.amazon.com/lambda/latest/dg/with-sqs.html) - -The following error handling options are only available for stream sources \(DynamoDB and Kinesis\): -+ `BisectBatchOnFunctionError` \- If the function returns an error, split the batch in two and retry\. -+ `DestinationConfig` \- Send discarded records to an Amazon SQS queue or Amazon SNS topic\. -+ `MaximumRecordAgeInSeconds` \- Discard records older than the specified age\. -+ `MaximumRetryAttempts` \- Discard records after the specified number of retries\. -+ `ParallelizationFactor` \- Process multiple batches from each shard concurrently\. - -## Request Syntax - -``` -POST /2015-03-31/event-source-mappings/ HTTP/1.1 -Content-type: application/json - -{ - "[BatchSize](#SSS-CreateEventSourceMapping-request-BatchSize)": number, - "[BisectBatchOnFunctionError](#SSS-CreateEventSourceMapping-request-BisectBatchOnFunctionError)": boolean, - "[DestinationConfig](#SSS-CreateEventSourceMapping-request-DestinationConfig)": { - "[OnFailure](API_DestinationConfig.md#SSS-Type-DestinationConfig-OnFailure)": { - "[Destination](API_OnFailure.md#SSS-Type-OnFailure-Destination)": "string" - }, - "[OnSuccess](API_DestinationConfig.md#SSS-Type-DestinationConfig-OnSuccess)": { - "[Destination](API_OnSuccess.md#SSS-Type-OnSuccess-Destination)": "string" - } - }, - "[Enabled](#SSS-CreateEventSourceMapping-request-Enabled)": boolean, - "[EventSourceArn](#SSS-CreateEventSourceMapping-request-EventSourceArn)": "string", - "[FunctionName](#SSS-CreateEventSourceMapping-request-FunctionName)": "string", - "[MaximumBatchingWindowInSeconds](#SSS-CreateEventSourceMapping-request-MaximumBatchingWindowInSeconds)": number, - "[MaximumRecordAgeInSeconds](#SSS-CreateEventSourceMapping-request-MaximumRecordAgeInSeconds)": number, - "[MaximumRetryAttempts](#SSS-CreateEventSourceMapping-request-MaximumRetryAttempts)": number, - "[ParallelizationFactor](#SSS-CreateEventSourceMapping-request-ParallelizationFactor)": number, - "[StartingPosition](#SSS-CreateEventSourceMapping-request-StartingPosition)": "string", - "[StartingPositionTimestamp](#SSS-CreateEventSourceMapping-request-StartingPositionTimestamp)": number -} -``` - -## URI Request Parameters - -The request does not use any URI parameters\. - -## Request Body - -The request accepts the following data in JSON format\. - - ** [BatchSize](#API_CreateEventSourceMapping_RequestSyntax) ** -The maximum number of items to retrieve in a single batch\. -+ **Amazon Kinesis** \- Default 100\. Max 10,000\. -+ **Amazon DynamoDB Streams** \- Default 100\. Max 1,000\. -+ **Amazon Simple Queue Service** \- Default 10\. Max 10\. -Type: Integer -Valid Range: Minimum value of 1\. Maximum value of 10000\. -Required: No - - ** [BisectBatchOnFunctionError](#API_CreateEventSourceMapping_RequestSyntax) ** -\(Streams\) If the function returns an error, split the batch in two and retry\. -Type: Boolean -Required: No - - ** [DestinationConfig](#API_CreateEventSourceMapping_RequestSyntax) ** -\(Streams\) An Amazon SQS queue or Amazon SNS topic destination for discarded records\. -Type: [DestinationConfig](API_DestinationConfig.md) object -Required: No - - ** [Enabled](#API_CreateEventSourceMapping_RequestSyntax) ** -Disables the event source mapping to pause polling and invocation\. -Type: Boolean -Required: No - - ** [EventSourceArn](#API_CreateEventSourceMapping_RequestSyntax) ** -The Amazon Resource Name \(ARN\) of the event source\. -+ **Amazon Kinesis** \- The ARN of the data stream or a stream consumer\. -+ **Amazon DynamoDB Streams** \- The ARN of the stream\. -+ **Amazon Simple Queue Service** \- The ARN of the queue\. -Type: String -Pattern: `arn:(aws[a-zA-Z0-9-]*):([a-zA-Z0-9\-])+:([a-z]{2}(-gov)?-[a-z]+-\d{1})?:(\d{12})?:(.*)` -Required: Yes - - ** [FunctionName](#API_CreateEventSourceMapping_RequestSyntax) ** -The name of the Lambda function\. - -**Name formats** -+ **Function name** \- `MyFunction`\. -+ **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:MyFunction`\. -+ **Version or Alias ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:MyFunction:PROD`\. -+ **Partial ARN** \- `123456789012:function:MyFunction`\. -The length constraint applies only to the full ARN\. If you specify only the function name, it's limited to 64 characters in length\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` -Required: Yes - - ** [MaximumBatchingWindowInSeconds](#API_CreateEventSourceMapping_RequestSyntax) ** -\(Streams\) The maximum amount of time to gather records before invoking the function, in seconds\. -Type: Integer -Valid Range: Minimum value of 0\. Maximum value of 300\. -Required: No - - ** [MaximumRecordAgeInSeconds](#API_CreateEventSourceMapping_RequestSyntax) ** -\(Streams\) The maximum age of a record that Lambda sends to a function for processing\. -Type: Integer -Valid Range: Minimum value of 60\. Maximum value of 604800\. -Required: No - - ** [MaximumRetryAttempts](#API_CreateEventSourceMapping_RequestSyntax) ** -\(Streams\) The maximum number of times to retry when the function returns an error\. -Type: Integer -Valid Range: Minimum value of 0\. Maximum value of 10000\. -Required: No - - ** [ParallelizationFactor](#API_CreateEventSourceMapping_RequestSyntax) ** -\(Streams\) The number of batches to process from each shard concurrently\. -Type: Integer -Valid Range: Minimum value of 1\. Maximum value of 10\. -Required: No - - ** [StartingPosition](#API_CreateEventSourceMapping_RequestSyntax) ** -The position in a stream from which to start reading\. Required for Amazon Kinesis and Amazon DynamoDB Streams sources\. `AT_TIMESTAMP` is only supported for Amazon Kinesis streams\. -Type: String -Valid Values:` TRIM_HORIZON | LATEST | AT_TIMESTAMP` -Required: No - - ** [StartingPositionTimestamp](#API_CreateEventSourceMapping_RequestSyntax) ** -With `StartingPosition` set to `AT_TIMESTAMP`, the time from which to start reading, in Unix time seconds\. -Type: Timestamp -Required: No - -## Response Syntax - -``` -HTTP/1.1 202 -Content-type: application/json - -{ - "[BatchSize](#SSS-CreateEventSourceMapping-response-BatchSize)": number, - "[BisectBatchOnFunctionError](#SSS-CreateEventSourceMapping-response-BisectBatchOnFunctionError)": boolean, - "[DestinationConfig](#SSS-CreateEventSourceMapping-response-DestinationConfig)": { - "[OnFailure](API_DestinationConfig.md#SSS-Type-DestinationConfig-OnFailure)": { - "[Destination](API_OnFailure.md#SSS-Type-OnFailure-Destination)": "string" - }, - "[OnSuccess](API_DestinationConfig.md#SSS-Type-DestinationConfig-OnSuccess)": { - "[Destination](API_OnSuccess.md#SSS-Type-OnSuccess-Destination)": "string" - } - }, - "[EventSourceArn](#SSS-CreateEventSourceMapping-response-EventSourceArn)": "string", - "[FunctionArn](#SSS-CreateEventSourceMapping-response-FunctionArn)": "string", - "[LastModified](#SSS-CreateEventSourceMapping-response-LastModified)": number, - "[LastProcessingResult](#SSS-CreateEventSourceMapping-response-LastProcessingResult)": "string", - "[MaximumBatchingWindowInSeconds](#SSS-CreateEventSourceMapping-response-MaximumBatchingWindowInSeconds)": number, - "[MaximumRecordAgeInSeconds](#SSS-CreateEventSourceMapping-response-MaximumRecordAgeInSeconds)": number, - "[MaximumRetryAttempts](#SSS-CreateEventSourceMapping-response-MaximumRetryAttempts)": number, - "[ParallelizationFactor](#SSS-CreateEventSourceMapping-response-ParallelizationFactor)": number, - "[State](#SSS-CreateEventSourceMapping-response-State)": "string", - "[StateTransitionReason](#SSS-CreateEventSourceMapping-response-StateTransitionReason)": "string", - "[UUID](#SSS-CreateEventSourceMapping-response-UUID)": "string" -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 202 response\. - -The following data is returned in JSON format by the service\. - - ** [BatchSize](#API_CreateEventSourceMapping_ResponseSyntax) ** -The maximum number of items to retrieve in a single batch\. -Type: Integer -Valid Range: Minimum value of 1\. Maximum value of 10000\. - - ** [BisectBatchOnFunctionError](#API_CreateEventSourceMapping_ResponseSyntax) ** -\(Streams\) If the function returns an error, split the batch in two and retry\. -Type: Boolean - - ** [DestinationConfig](#API_CreateEventSourceMapping_ResponseSyntax) ** -\(Streams\) An Amazon SQS queue or Amazon SNS topic destination for discarded records\. -Type: [DestinationConfig](API_DestinationConfig.md) object - - ** [EventSourceArn](#API_CreateEventSourceMapping_ResponseSyntax) ** -The Amazon Resource Name \(ARN\) of the event source\. -Type: String -Pattern: `arn:(aws[a-zA-Z0-9-]*):([a-zA-Z0-9\-])+:([a-z]{2}(-gov)?-[a-z]+-\d{1})?:(\d{12})?:(.*)` - - ** [FunctionArn](#API_CreateEventSourceMapping_ResponseSyntax) ** -The ARN of the Lambda function\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}(-gov)?-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [LastModified](#API_CreateEventSourceMapping_ResponseSyntax) ** -The date that the event source mapping was last updated, or its state changed, in Unix time seconds\. -Type: Timestamp - - ** [LastProcessingResult](#API_CreateEventSourceMapping_ResponseSyntax) ** -The result of the last AWS Lambda invocation of your Lambda function\. -Type: String - - ** [MaximumBatchingWindowInSeconds](#API_CreateEventSourceMapping_ResponseSyntax) ** -\(Streams\) The maximum amount of time to gather records before invoking the function, in seconds\. -Type: Integer -Valid Range: Minimum value of 0\. Maximum value of 300\. - - ** [MaximumRecordAgeInSeconds](#API_CreateEventSourceMapping_ResponseSyntax) ** -\(Streams\) The maximum age of a record that Lambda sends to a function for processing\. -Type: Integer -Valid Range: Minimum value of 60\. Maximum value of 604800\. - - ** [MaximumRetryAttempts](#API_CreateEventSourceMapping_ResponseSyntax) ** -\(Streams\) The maximum number of times to retry when the function returns an error\. -Type: Integer -Valid Range: Minimum value of 0\. Maximum value of 10000\. - - ** [ParallelizationFactor](#API_CreateEventSourceMapping_ResponseSyntax) ** -\(Streams\) The number of batches to process from each shard concurrently\. -Type: Integer -Valid Range: Minimum value of 1\. Maximum value of 10\. - - ** [State](#API_CreateEventSourceMapping_ResponseSyntax) ** -The state of the event source mapping\. It can be one of the following: `Creating`, `Enabling`, `Enabled`, `Disabling`, `Disabled`, `Updating`, or `Deleting`\. -Type: String - - ** [StateTransitionReason](#API_CreateEventSourceMapping_ResponseSyntax) ** -Indicates whether the last change to the event source mapping was made by a user, or by the Lambda service\. -Type: String - - ** [UUID](#API_CreateEventSourceMapping_ResponseSyntax) ** -The identifier of the event source mapping\. -Type: String - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceConflictException** -The resource already exists, or another operation is in progress\. -HTTP Status Code: 409 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/CreateEventSourceMapping) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/CreateEventSourceMapping) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/CreateEventSourceMapping) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/CreateEventSourceMapping) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/CreateEventSourceMapping) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/CreateEventSourceMapping) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/CreateEventSourceMapping) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/CreateEventSourceMapping) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/CreateEventSourceMapping) \ No newline at end of file diff --git a/doc_source/API_CreateFunction.md b/doc_source/API_CreateFunction.md deleted file mode 100644 index 7efa7b52..00000000 --- a/doc_source/API_CreateFunction.md +++ /dev/null @@ -1,387 +0,0 @@ -# CreateFunction - -Creates a Lambda function\. To create a function, you need a [deployment package](https://docs.aws.amazon.com/lambda/latest/dg/deployment-package-v2.html) and an [execution role](https://docs.aws.amazon.com/lambda/latest/dg/intro-permission-model.html#lambda-intro-execution-role)\. The deployment package contains your function code\. The execution role grants the function permission to use AWS services, such as Amazon CloudWatch Logs for log streaming and AWS X\-Ray for request tracing\. - -When you create a function, Lambda provisions an instance of the function and its supporting resources\. If your function connects to a VPC, this process can take a minute or so\. During this time, you can't invoke or modify the function\. The `State`, `StateReason`, and `StateReasonCode` fields in the response from [GetFunctionConfiguration](API_GetFunctionConfiguration.md) indicate when the function is ready to invoke\. For more information, see [Function States](https://docs.aws.amazon.com/lambda/latest/dg/functions-states.html)\. - -A function has an unpublished version, and can have published versions and aliases\. The unpublished version changes when you update your function's code and configuration\. A published version is a snapshot of your function code and configuration that can't be changed\. An alias is a named resource that maps to a version, and can be changed to map to a different version\. Use the `Publish` parameter to create version `1` of your function from its initial configuration\. - -The other parameters let you configure version\-specific and function\-level settings\. You can modify version\-specific settings later with [UpdateFunctionConfiguration](API_UpdateFunctionConfiguration.md)\. Function\-level settings apply to both the unpublished and published versions of the function, and include tags \([TagResource](API_TagResource.md)\) and per\-function concurrency limits \([PutFunctionConcurrency](API_PutFunctionConcurrency.md)\)\. - -If another account or an AWS service invokes your function, use [AddPermission](API_AddPermission.md) to grant permission by creating a resource\-based IAM policy\. You can grant permissions at the function level, on a version, or on an alias\. - -To invoke your function directly, use [Invoke](API_Invoke.md)\. To invoke your function in response to events in other AWS services, create an event source mapping \([CreateEventSourceMapping](API_CreateEventSourceMapping.md)\), or configure a function trigger in the other service\. For more information, see [Invoking Functions](https://docs.aws.amazon.com/lambda/latest/dg/lambda-invocation.html)\. - -## Request Syntax - -``` -POST /2015-03-31/functions HTTP/1.1 -Content-type: application/json - -{ - "[Code](#SSS-CreateFunction-request-Code)": { - "[S3Bucket](API_FunctionCode.md#SSS-Type-FunctionCode-S3Bucket)": "string", - "[S3Key](API_FunctionCode.md#SSS-Type-FunctionCode-S3Key)": "string", - "[S3ObjectVersion](API_FunctionCode.md#SSS-Type-FunctionCode-S3ObjectVersion)": "string", - "[ZipFile](API_FunctionCode.md#SSS-Type-FunctionCode-ZipFile)": blob - }, - "[DeadLetterConfig](#SSS-CreateFunction-request-DeadLetterConfig)": { - "[TargetArn](API_DeadLetterConfig.md#SSS-Type-DeadLetterConfig-TargetArn)": "string" - }, - "[Description](#SSS-CreateFunction-request-Description)": "string", - "[Environment](#SSS-CreateFunction-request-Environment)": { - "[Variables](API_Environment.md#SSS-Type-Environment-Variables)": { - "string" : "string" - } - }, - "[FunctionName](#SSS-CreateFunction-request-FunctionName)": "string", - "[Handler](#SSS-CreateFunction-request-Handler)": "string", - "[KMSKeyArn](#SSS-CreateFunction-request-KMSKeyArn)": "string", - "[Layers](#SSS-CreateFunction-request-Layers)": [ "string" ], - "[MemorySize](#SSS-CreateFunction-request-MemorySize)": number, - "[Publish](#SSS-CreateFunction-request-Publish)": boolean, - "[Role](#SSS-CreateFunction-request-Role)": "string", - "[Runtime](#SSS-CreateFunction-request-Runtime)": "string", - "[Tags](#SSS-CreateFunction-request-Tags)": { - "string" : "string" - }, - "[Timeout](#SSS-CreateFunction-request-Timeout)": number, - "[TracingConfig](#SSS-CreateFunction-request-TracingConfig)": { - "[Mode](API_TracingConfig.md#SSS-Type-TracingConfig-Mode)": "string" - }, - "[VpcConfig](#SSS-CreateFunction-request-VpcConfig)": { - "[SecurityGroupIds](API_VpcConfig.md#SSS-Type-VpcConfig-SecurityGroupIds)": [ "string" ], - "[SubnetIds](API_VpcConfig.md#SSS-Type-VpcConfig-SubnetIds)": [ "string" ] - } -} -``` - -## URI Request Parameters - -The request does not use any URI parameters\. - -## Request Body - -The request accepts the following data in JSON format\. - - ** [Code](#API_CreateFunction_RequestSyntax) ** -The code for the function\. -Type: [FunctionCode](API_FunctionCode.md) object -Required: Yes - - ** [DeadLetterConfig](#API_CreateFunction_RequestSyntax) ** -A dead letter queue configuration that specifies the queue or topic where Lambda sends asynchronous events when they fail processing\. For more information, see [Dead Letter Queues](https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html#dlq)\. -Type: [DeadLetterConfig](API_DeadLetterConfig.md) object -Required: No - - ** [Description](#API_CreateFunction_RequestSyntax) ** -A description of the function\. -Type: String -Length Constraints: Minimum length of 0\. Maximum length of 256\. -Required: No - - ** [Environment](#API_CreateFunction_RequestSyntax) ** -Environment variables that are accessible from function code during execution\. -Type: [Environment](API_Environment.md) object -Required: No - - ** [FunctionName](#API_CreateFunction_RequestSyntax) ** -The name of the Lambda function\. - -**Name formats** -+ **Function name** \- `my-function`\. -+ **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:my-function`\. -+ **Partial ARN** \- `123456789012:function:my-function`\. -The length constraint applies only to the full ARN\. If you specify only the function name, it is limited to 64 characters in length\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` -Required: Yes - - ** [Handler](#API_CreateFunction_RequestSyntax) ** -The name of the method within your code that Lambda calls to execute your function\. The format includes the file name\. It can also include namespaces and other qualifiers, depending on the runtime\. For more information, see [Programming Model](https://docs.aws.amazon.com/lambda/latest/dg/programming-model-v2.html)\. -Type: String -Length Constraints: Maximum length of 128\. -Pattern: `[^\s]+` -Required: Yes - - ** [KMSKeyArn](#API_CreateFunction_RequestSyntax) ** -The ARN of the AWS Key Management Service \(AWS KMS\) key that's used to encrypt your function's environment variables\. If it's not provided, AWS Lambda uses a default service key\. -Type: String -Pattern: `(arn:(aws[a-zA-Z-]*)?:[a-z0-9-.]+:.*)|()` -Required: No - - ** [Layers](#API_CreateFunction_RequestSyntax) ** -A list of [function layers](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) to add to the function's execution environment\. Specify each layer by its ARN, including the version\. -Type: Array of strings -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `arn:[a-zA-Z0-9-]+:lambda:[a-zA-Z0-9-]+:\d{12}:layer:[a-zA-Z0-9-_]+:[0-9]+` -Required: No - - ** [MemorySize](#API_CreateFunction_RequestSyntax) ** -The amount of memory that your function has access to\. Increasing the function's memory also increases its CPU allocation\. The default value is 128 MB\. The value must be a multiple of 64 MB\. -Type: Integer -Valid Range: Minimum value of 128\. Maximum value of 3008\. -Required: No - - ** [Publish](#API_CreateFunction_RequestSyntax) ** -Set to true to publish the first version of the function during creation\. -Type: Boolean -Required: No - - ** [Role](#API_CreateFunction_RequestSyntax) ** -The Amazon Resource Name \(ARN\) of the function's execution role\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:iam::\d{12}:role/?[a-zA-Z_0-9+=,.@\-_/]+` -Required: Yes - - ** [Runtime](#API_CreateFunction_RequestSyntax) ** -The identifier of the function's [runtime](https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html)\. -Type: String -Valid Values:` nodejs10.x | nodejs12.x | java8 | java11 | python2.7 | python3.6 | python3.7 | python3.8 | dotnetcore2.1 | go1.x | ruby2.5 | ruby2.7 | provided` -Required: Yes - - ** [Tags](#API_CreateFunction_RequestSyntax) ** -A list of [tags](https://docs.aws.amazon.com/lambda/latest/dg/tagging.html) to apply to the function\. -Type: String to string map -Required: No - - ** [Timeout](#API_CreateFunction_RequestSyntax) ** -The amount of time that Lambda allows a function to run before stopping it\. The default is 3 seconds\. The maximum allowed value is 900 seconds\. -Type: Integer -Valid Range: Minimum value of 1\. -Required: No - - ** [TracingConfig](#API_CreateFunction_RequestSyntax) ** -Set `Mode` to `Active` to sample and trace a subset of incoming requests with AWS X\-Ray\. -Type: [TracingConfig](API_TracingConfig.md) object -Required: No - - ** [VpcConfig](#API_CreateFunction_RequestSyntax) ** -For network connectivity to AWS resources in a VPC, specify a list of security groups and subnets in the VPC\. When you connect a function to a VPC, it can only access resources and the internet through that VPC\. For more information, see [VPC Settings](https://docs.aws.amazon.com/lambda/latest/dg/configuration-vpc.html)\. -Type: [VpcConfig](API_VpcConfig.md) object -Required: No - -## Response Syntax - -``` -HTTP/1.1 201 -Content-type: application/json - -{ - "[CodeSha256](#SSS-CreateFunction-response-CodeSha256)": "string", - "[CodeSize](#SSS-CreateFunction-response-CodeSize)": number, - "[DeadLetterConfig](#SSS-CreateFunction-response-DeadLetterConfig)": { - "[TargetArn](API_DeadLetterConfig.md#SSS-Type-DeadLetterConfig-TargetArn)": "string" - }, - "[Description](#SSS-CreateFunction-response-Description)": "string", - "[Environment](#SSS-CreateFunction-response-Environment)": { - "[Error](API_EnvironmentResponse.md#SSS-Type-EnvironmentResponse-Error)": { - "[ErrorCode](API_EnvironmentError.md#SSS-Type-EnvironmentError-ErrorCode)": "string", - "[Message](API_EnvironmentError.md#SSS-Type-EnvironmentError-Message)": "string" - }, - "[Variables](API_EnvironmentResponse.md#SSS-Type-EnvironmentResponse-Variables)": { - "string" : "string" - } - }, - "[FunctionArn](#SSS-CreateFunction-response-FunctionArn)": "string", - "[FunctionName](#SSS-CreateFunction-response-FunctionName)": "string", - "[Handler](#SSS-CreateFunction-response-Handler)": "string", - "[KMSKeyArn](#SSS-CreateFunction-response-KMSKeyArn)": "string", - "[LastModified](#SSS-CreateFunction-response-LastModified)": "string", - "[LastUpdateStatus](#SSS-CreateFunction-response-LastUpdateStatus)": "string", - "[LastUpdateStatusReason](#SSS-CreateFunction-response-LastUpdateStatusReason)": "string", - "[LastUpdateStatusReasonCode](#SSS-CreateFunction-response-LastUpdateStatusReasonCode)": "string", - "[Layers](#SSS-CreateFunction-response-Layers)": [ - { - "[Arn](API_Layer.md#SSS-Type-Layer-Arn)": "string", - "[CodeSize](API_Layer.md#SSS-Type-Layer-CodeSize)": number - } - ], - "[MasterArn](#SSS-CreateFunction-response-MasterArn)": "string", - "[MemorySize](#SSS-CreateFunction-response-MemorySize)": number, - "[RevisionId](#SSS-CreateFunction-response-RevisionId)": "string", - "[Role](#SSS-CreateFunction-response-Role)": "string", - "[Runtime](#SSS-CreateFunction-response-Runtime)": "string", - "[State](#SSS-CreateFunction-response-State)": "string", - "[StateReason](#SSS-CreateFunction-response-StateReason)": "string", - "[StateReasonCode](#SSS-CreateFunction-response-StateReasonCode)": "string", - "[Timeout](#SSS-CreateFunction-response-Timeout)": number, - "[TracingConfig](#SSS-CreateFunction-response-TracingConfig)": { - "[Mode](API_TracingConfigResponse.md#SSS-Type-TracingConfigResponse-Mode)": "string" - }, - "[Version](#SSS-CreateFunction-response-Version)": "string", - "[VpcConfig](#SSS-CreateFunction-response-VpcConfig)": { - "[SecurityGroupIds](API_VpcConfigResponse.md#SSS-Type-VpcConfigResponse-SecurityGroupIds)": [ "string" ], - "[SubnetIds](API_VpcConfigResponse.md#SSS-Type-VpcConfigResponse-SubnetIds)": [ "string" ], - "[VpcId](API_VpcConfigResponse.md#SSS-Type-VpcConfigResponse-VpcId)": "string" - } -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 201 response\. - -The following data is returned in JSON format by the service\. - - ** [CodeSha256](#API_CreateFunction_ResponseSyntax) ** -The SHA256 hash of the function's deployment package\. -Type: String - - ** [CodeSize](#API_CreateFunction_ResponseSyntax) ** -The size of the function's deployment package, in bytes\. -Type: Long - - ** [DeadLetterConfig](#API_CreateFunction_ResponseSyntax) ** -The function's dead letter queue\. -Type: [DeadLetterConfig](API_DeadLetterConfig.md) object - - ** [Description](#API_CreateFunction_ResponseSyntax) ** -The function's description\. -Type: String -Length Constraints: Minimum length of 0\. Maximum length of 256\. - - ** [Environment](#API_CreateFunction_ResponseSyntax) ** -The function's environment variables\. -Type: [EnvironmentResponse](API_EnvironmentResponse.md) object - - ** [FunctionArn](#API_CreateFunction_ResponseSyntax) ** -The function's Amazon Resource Name \(ARN\)\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}(-gov)?-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_\.]+(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [FunctionName](#API_CreateFunction_ResponseSyntax) ** -The name of the function\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 170\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_\.]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [Handler](#API_CreateFunction_ResponseSyntax) ** -The function that Lambda calls to begin executing your function\. -Type: String -Length Constraints: Maximum length of 128\. -Pattern: `[^\s]+` - - ** [KMSKeyArn](#API_CreateFunction_ResponseSyntax) ** -The KMS key that's used to encrypt the function's environment variables\. This key is only returned if you've configured a customer managed CMK\. -Type: String -Pattern: `(arn:(aws[a-zA-Z-]*)?:[a-z0-9-.]+:.*)|()` - - ** [LastModified](#API_CreateFunction_ResponseSyntax) ** -The date and time that the function was last updated, in [ISO\-8601 format](https://www.w3.org/TR/NOTE-datetime) \(YYYY\-MM\-DDThh:mm:ss\.sTZD\)\. -Type: String - - ** [LastUpdateStatus](#API_CreateFunction_ResponseSyntax) ** -The status of the last update that was performed on the function\. This is first set to `Successful` after function creation completes\. -Type: String -Valid Values:` Successful | Failed | InProgress` - - ** [LastUpdateStatusReason](#API_CreateFunction_ResponseSyntax) ** -The reason for the last update that was performed on the function\. -Type: String - - ** [LastUpdateStatusReasonCode](#API_CreateFunction_ResponseSyntax) ** -The reason code for the last update that was performed on the function\. -Type: String -Valid Values:` EniLimitExceeded | InsufficientRolePermissions | InvalidConfiguration | InternalError | SubnetOutOfIPAddresses | InvalidSubnet | InvalidSecurityGroup` - - ** [Layers](#API_CreateFunction_ResponseSyntax) ** -The function's [ layers](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)\. -Type: Array of [Layer](API_Layer.md) objects - - ** [MasterArn](#API_CreateFunction_ResponseSyntax) ** -For Lambda@Edge functions, the ARN of the master function\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}(-gov)?-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [MemorySize](#API_CreateFunction_ResponseSyntax) ** -The memory that's allocated to the function\. -Type: Integer -Valid Range: Minimum value of 128\. Maximum value of 3008\. - - ** [RevisionId](#API_CreateFunction_ResponseSyntax) ** -The latest updated revision of the function or alias\. -Type: String - - ** [Role](#API_CreateFunction_ResponseSyntax) ** -The function's execution role\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:iam::\d{12}:role/?[a-zA-Z_0-9+=,.@\-_/]+` - - ** [Runtime](#API_CreateFunction_ResponseSyntax) ** -The runtime environment for the Lambda function\. -Type: String -Valid Values:` nodejs10.x | nodejs12.x | java8 | java11 | python2.7 | python3.6 | python3.7 | python3.8 | dotnetcore2.1 | go1.x | ruby2.5 | ruby2.7 | provided` - - ** [State](#API_CreateFunction_ResponseSyntax) ** -The current state of the function\. When the state is `Inactive`, you can reactivate the function by invoking it\. -Type: String -Valid Values:` Pending | Active | Inactive | Failed` - - ** [StateReason](#API_CreateFunction_ResponseSyntax) ** -The reason for the function's current state\. -Type: String - - ** [StateReasonCode](#API_CreateFunction_ResponseSyntax) ** -The reason code for the function's current state\. When the code is `Creating`, you can't invoke or modify the function\. -Type: String -Valid Values:` Idle | Creating | Restoring | EniLimitExceeded | InsufficientRolePermissions | InvalidConfiguration | InternalError | SubnetOutOfIPAddresses | InvalidSubnet | InvalidSecurityGroup` - - ** [Timeout](#API_CreateFunction_ResponseSyntax) ** -The amount of time that Lambda allows a function to run before stopping it\. -Type: Integer -Valid Range: Minimum value of 1\. - - ** [TracingConfig](#API_CreateFunction_ResponseSyntax) ** -The function's AWS X\-Ray tracing configuration\. -Type: [TracingConfigResponse](API_TracingConfigResponse.md) object - - ** [Version](#API_CreateFunction_ResponseSyntax) ** -The version of the Lambda function\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 1024\. -Pattern: `(\$LATEST|[0-9]+)` - - ** [VpcConfig](#API_CreateFunction_ResponseSyntax) ** -The function's networking configuration\. -Type: [VpcConfigResponse](API_VpcConfigResponse.md) object - -## Errors - - **CodeStorageExceededException** -You have exceeded your maximum total code size per account\. [Learn more](https://docs.aws.amazon.com/lambda/latest/dg/limits.html) -HTTP Status Code: 400 - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceConflictException** -The resource already exists, or another operation is in progress\. -HTTP Status Code: 409 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/CreateFunction) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/CreateFunction) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/CreateFunction) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/CreateFunction) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/CreateFunction) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/CreateFunction) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/CreateFunction) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/CreateFunction) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/CreateFunction) \ No newline at end of file diff --git a/doc_source/API_DeadLetterConfig.md b/doc_source/API_DeadLetterConfig.md deleted file mode 100644 index 091cb236..00000000 --- a/doc_source/API_DeadLetterConfig.md +++ /dev/null @@ -1,19 +0,0 @@ -# DeadLetterConfig - -The [dead\-letter queue](https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html#dlq) for failed asynchronous invocations\. - -## Contents - - **TargetArn** -The Amazon Resource Name \(ARN\) of an Amazon SQS queue or Amazon SNS topic\. -Type: String -Pattern: `(arn:(aws[a-zA-Z-]*)?:[a-z0-9-.]+:.*)|()` -Required: No - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/DeadLetterConfig) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/DeadLetterConfig) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/DeadLetterConfig) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/DeadLetterConfig) \ No newline at end of file diff --git a/doc_source/API_DeleteAlias.md b/doc_source/API_DeleteAlias.md deleted file mode 100644 index 1170a96e..00000000 --- a/doc_source/API_DeleteAlias.md +++ /dev/null @@ -1,74 +0,0 @@ -# DeleteAlias - -Deletes a Lambda function [alias](https://docs.aws.amazon.com/lambda/latest/dg/versioning-aliases.html)\. - -## Request Syntax - -``` -DELETE /2015-03-31/functions/FunctionName/aliases/Name HTTP/1.1 -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [FunctionName](#API_DeleteAlias_RequestSyntax) ** -The name of the Lambda function\. - -**Name formats** -+ **Function name** \- `MyFunction`\. -+ **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:MyFunction`\. -+ **Partial ARN** \- `123456789012:function:MyFunction`\. -The length constraint applies only to the full ARN\. If you specify only the function name, it is limited to 64 characters in length\. -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [Name](#API_DeleteAlias_RequestSyntax) ** -The name of the alias\. -Length Constraints: Minimum length of 1\. Maximum length of 128\. -Pattern: `(?!^[0-9]+$)([a-zA-Z0-9-_]+)` - -## Request Body - -The request does not have a request body\. - -## Response Syntax - -``` -HTTP/1.1 204 -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body\. - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceConflictException** -The resource already exists, or another operation is in progress\. -HTTP Status Code: 409 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/DeleteAlias) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/DeleteAlias) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/DeleteAlias) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/DeleteAlias) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/DeleteAlias) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/DeleteAlias) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/DeleteAlias) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/DeleteAlias) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/DeleteAlias) \ No newline at end of file diff --git a/doc_source/API_DeleteEventSourceMapping.md b/doc_source/API_DeleteEventSourceMapping.md deleted file mode 100644 index 5c0913cd..00000000 --- a/doc_source/API_DeleteEventSourceMapping.md +++ /dev/null @@ -1,157 +0,0 @@ -# DeleteEventSourceMapping - -Deletes an [event source mapping](https://docs.aws.amazon.com/lambda/latest/dg/intro-invocation-modes.html)\. You can get the identifier of a mapping from the output of [ListEventSourceMappings](API_ListEventSourceMappings.md)\. - -When you delete an event source mapping, it enters a `Deleting` state and might not be completely deleted for several seconds\. - -## Request Syntax - -``` -DELETE /2015-03-31/event-source-mappings/UUID HTTP/1.1 -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [UUID](#API_DeleteEventSourceMapping_RequestSyntax) ** -The identifier of the event source mapping\. - -## Request Body - -The request does not have a request body\. - -## Response Syntax - -``` -HTTP/1.1 202 -Content-type: application/json - -{ - "[BatchSize](#SSS-DeleteEventSourceMapping-response-BatchSize)": number, - "[BisectBatchOnFunctionError](#SSS-DeleteEventSourceMapping-response-BisectBatchOnFunctionError)": boolean, - "[DestinationConfig](#SSS-DeleteEventSourceMapping-response-DestinationConfig)": { - "[OnFailure](API_DestinationConfig.md#SSS-Type-DestinationConfig-OnFailure)": { - "[Destination](API_OnFailure.md#SSS-Type-OnFailure-Destination)": "string" - }, - "[OnSuccess](API_DestinationConfig.md#SSS-Type-DestinationConfig-OnSuccess)": { - "[Destination](API_OnSuccess.md#SSS-Type-OnSuccess-Destination)": "string" - } - }, - "[EventSourceArn](#SSS-DeleteEventSourceMapping-response-EventSourceArn)": "string", - "[FunctionArn](#SSS-DeleteEventSourceMapping-response-FunctionArn)": "string", - "[LastModified](#SSS-DeleteEventSourceMapping-response-LastModified)": number, - "[LastProcessingResult](#SSS-DeleteEventSourceMapping-response-LastProcessingResult)": "string", - "[MaximumBatchingWindowInSeconds](#SSS-DeleteEventSourceMapping-response-MaximumBatchingWindowInSeconds)": number, - "[MaximumRecordAgeInSeconds](#SSS-DeleteEventSourceMapping-response-MaximumRecordAgeInSeconds)": number, - "[MaximumRetryAttempts](#SSS-DeleteEventSourceMapping-response-MaximumRetryAttempts)": number, - "[ParallelizationFactor](#SSS-DeleteEventSourceMapping-response-ParallelizationFactor)": number, - "[State](#SSS-DeleteEventSourceMapping-response-State)": "string", - "[StateTransitionReason](#SSS-DeleteEventSourceMapping-response-StateTransitionReason)": "string", - "[UUID](#SSS-DeleteEventSourceMapping-response-UUID)": "string" -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 202 response\. - -The following data is returned in JSON format by the service\. - - ** [BatchSize](#API_DeleteEventSourceMapping_ResponseSyntax) ** -The maximum number of items to retrieve in a single batch\. -Type: Integer -Valid Range: Minimum value of 1\. Maximum value of 10000\. - - ** [BisectBatchOnFunctionError](#API_DeleteEventSourceMapping_ResponseSyntax) ** -\(Streams\) If the function returns an error, split the batch in two and retry\. -Type: Boolean - - ** [DestinationConfig](#API_DeleteEventSourceMapping_ResponseSyntax) ** -\(Streams\) An Amazon SQS queue or Amazon SNS topic destination for discarded records\. -Type: [DestinationConfig](API_DestinationConfig.md) object - - ** [EventSourceArn](#API_DeleteEventSourceMapping_ResponseSyntax) ** -The Amazon Resource Name \(ARN\) of the event source\. -Type: String -Pattern: `arn:(aws[a-zA-Z0-9-]*):([a-zA-Z0-9\-])+:([a-z]{2}(-gov)?-[a-z]+-\d{1})?:(\d{12})?:(.*)` - - ** [FunctionArn](#API_DeleteEventSourceMapping_ResponseSyntax) ** -The ARN of the Lambda function\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}(-gov)?-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [LastModified](#API_DeleteEventSourceMapping_ResponseSyntax) ** -The date that the event source mapping was last updated, or its state changed, in Unix time seconds\. -Type: Timestamp - - ** [LastProcessingResult](#API_DeleteEventSourceMapping_ResponseSyntax) ** -The result of the last AWS Lambda invocation of your Lambda function\. -Type: String - - ** [MaximumBatchingWindowInSeconds](#API_DeleteEventSourceMapping_ResponseSyntax) ** -\(Streams\) The maximum amount of time to gather records before invoking the function, in seconds\. -Type: Integer -Valid Range: Minimum value of 0\. Maximum value of 300\. - - ** [MaximumRecordAgeInSeconds](#API_DeleteEventSourceMapping_ResponseSyntax) ** -\(Streams\) The maximum age of a record that Lambda sends to a function for processing\. -Type: Integer -Valid Range: Minimum value of 60\. Maximum value of 604800\. - - ** [MaximumRetryAttempts](#API_DeleteEventSourceMapping_ResponseSyntax) ** -\(Streams\) The maximum number of times to retry when the function returns an error\. -Type: Integer -Valid Range: Minimum value of 0\. Maximum value of 10000\. - - ** [ParallelizationFactor](#API_DeleteEventSourceMapping_ResponseSyntax) ** -\(Streams\) The number of batches to process from each shard concurrently\. -Type: Integer -Valid Range: Minimum value of 1\. Maximum value of 10\. - - ** [State](#API_DeleteEventSourceMapping_ResponseSyntax) ** -The state of the event source mapping\. It can be one of the following: `Creating`, `Enabling`, `Enabled`, `Disabling`, `Disabled`, `Updating`, or `Deleting`\. -Type: String - - ** [StateTransitionReason](#API_DeleteEventSourceMapping_ResponseSyntax) ** -Indicates whether the last change to the event source mapping was made by a user, or by the Lambda service\. -Type: String - - ** [UUID](#API_DeleteEventSourceMapping_ResponseSyntax) ** -The identifier of the event source mapping\. -Type: String - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceInUseException** -The operation conflicts with the resource's availability\. For example, you attempted to update an EventSource Mapping in CREATING, or tried to delete a EventSource mapping currently in the UPDATING state\. -HTTP Status Code: 400 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/DeleteEventSourceMapping) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/DeleteEventSourceMapping) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/DeleteEventSourceMapping) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/DeleteEventSourceMapping) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/DeleteEventSourceMapping) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/DeleteEventSourceMapping) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/DeleteEventSourceMapping) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/DeleteEventSourceMapping) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/DeleteEventSourceMapping) \ No newline at end of file diff --git a/doc_source/API_DeleteFunction.md b/doc_source/API_DeleteFunction.md deleted file mode 100644 index 2bba33d3..00000000 --- a/doc_source/API_DeleteFunction.md +++ /dev/null @@ -1,80 +0,0 @@ -# DeleteFunction - -Deletes a Lambda function\. To delete a specific function version, use the `Qualifier` parameter\. Otherwise, all versions and aliases are deleted\. - -To delete Lambda event source mappings that invoke a function, use [DeleteEventSourceMapping](API_DeleteEventSourceMapping.md)\. For AWS services and resources that invoke your function directly, delete the trigger in the service where you originally configured it\. - -## Request Syntax - -``` -DELETE /2015-03-31/functions/FunctionName?Qualifier=Qualifier HTTP/1.1 -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [FunctionName](#API_DeleteFunction_RequestSyntax) ** -The name of the Lambda function or version\. - -**Name formats** -+ **Function name** \- `my-function` \(name\-only\), `my-function:1` \(with version\)\. -+ **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:my-function`\. -+ **Partial ARN** \- `123456789012:function:my-function`\. -You can append a version number or alias to any of the formats\. The length constraint applies only to the full ARN\. If you specify only the function name, it is limited to 64 characters in length\. -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [Qualifier](#API_DeleteFunction_RequestSyntax) ** -Specify a version to delete\. You can't delete a version that's referenced by an alias\. -Length Constraints: Minimum length of 1\. Maximum length of 128\. -Pattern: `(|[a-zA-Z0-9$_-]+)` - -## Request Body - -The request does not have a request body\. - -## Response Syntax - -``` -HTTP/1.1 204 -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body\. - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceConflictException** -The resource already exists, or another operation is in progress\. -HTTP Status Code: 409 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/DeleteFunction) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/DeleteFunction) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/DeleteFunction) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/DeleteFunction) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/DeleteFunction) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/DeleteFunction) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/DeleteFunction) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/DeleteFunction) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/DeleteFunction) \ No newline at end of file diff --git a/doc_source/API_DeleteFunctionConcurrency.md b/doc_source/API_DeleteFunctionConcurrency.md deleted file mode 100644 index 66a16851..00000000 --- a/doc_source/API_DeleteFunctionConcurrency.md +++ /dev/null @@ -1,73 +0,0 @@ -# DeleteFunctionConcurrency - -Removes a concurrent execution limit from a function\. - -## Request Syntax - -``` -DELETE /2017-10-31/functions/FunctionName/concurrency HTTP/1.1 -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [FunctionName](#API_DeleteFunctionConcurrency_RequestSyntax) ** -The name of the Lambda function\. - -**Name formats** -+ **Function name** \- `my-function`\. -+ **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:my-function`\. -+ **Partial ARN** \- `123456789012:function:my-function`\. -The length constraint applies only to the full ARN\. If you specify only the function name, it is limited to 64 characters in length\. -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - -## Request Body - -The request does not have a request body\. - -## Response Syntax - -``` -HTTP/1.1 204 -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body\. - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceConflictException** -The resource already exists, or another operation is in progress\. -HTTP Status Code: 409 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/DeleteFunctionConcurrency) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/DeleteFunctionConcurrency) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/DeleteFunctionConcurrency) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/DeleteFunctionConcurrency) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/DeleteFunctionConcurrency) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/DeleteFunctionConcurrency) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/DeleteFunctionConcurrency) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/DeleteFunctionConcurrency) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/DeleteFunctionConcurrency) \ No newline at end of file diff --git a/doc_source/API_DeleteFunctionEventInvokeConfig.md b/doc_source/API_DeleteFunctionEventInvokeConfig.md deleted file mode 100644 index 8f9510ed..00000000 --- a/doc_source/API_DeleteFunctionEventInvokeConfig.md +++ /dev/null @@ -1,76 +0,0 @@ -# DeleteFunctionEventInvokeConfig - -Deletes the configuration for asynchronous invocation for a function, version, or alias\. - -To configure options for asynchronous invocation, use [PutFunctionEventInvokeConfig](API_PutFunctionEventInvokeConfig.md)\. - -## Request Syntax - -``` -DELETE /2019-09-25/functions/FunctionName/event-invoke-config?Qualifier=Qualifier HTTP/1.1 -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [FunctionName](#API_DeleteFunctionEventInvokeConfig_RequestSyntax) ** -The name of the Lambda function, version, or alias\. - -**Name formats** -+ **Function name** \- `my-function` \(name\-only\), `my-function:v1` \(with alias\)\. -+ **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:my-function`\. -+ **Partial ARN** \- `123456789012:function:my-function`\. -You can append a version number or alias to any of the formats\. The length constraint applies only to the full ARN\. If you specify only the function name, it is limited to 64 characters in length\. -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [Qualifier](#API_DeleteFunctionEventInvokeConfig_RequestSyntax) ** -A version number or alias name\. -Length Constraints: Minimum length of 1\. Maximum length of 128\. -Pattern: `(|[a-zA-Z0-9$_-]+)` - -## Request Body - -The request does not have a request body\. - -## Response Syntax - -``` -HTTP/1.1 204 -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body\. - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/DeleteFunctionEventInvokeConfig) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/DeleteFunctionEventInvokeConfig) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/DeleteFunctionEventInvokeConfig) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/DeleteFunctionEventInvokeConfig) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/DeleteFunctionEventInvokeConfig) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/DeleteFunctionEventInvokeConfig) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/DeleteFunctionEventInvokeConfig) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/DeleteFunctionEventInvokeConfig) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/DeleteFunctionEventInvokeConfig) \ No newline at end of file diff --git a/doc_source/API_DeleteLayerVersion.md b/doc_source/API_DeleteLayerVersion.md deleted file mode 100644 index 184a3ee5..00000000 --- a/doc_source/API_DeleteLayerVersion.md +++ /dev/null @@ -1,58 +0,0 @@ -# DeleteLayerVersion - -Deletes a version of an [AWS Lambda layer](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)\. Deleted versions can no longer be viewed or added to functions\. To avoid breaking functions, a copy of the version remains in Lambda until no functions refer to it\. - -## Request Syntax - -``` -DELETE /2018-10-31/layers/LayerName/versions/VersionNumber HTTP/1.1 -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [LayerName](#API_DeleteLayerVersion_RequestSyntax) ** -The name or Amazon Resource Name \(ARN\) of the layer\. -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:[a-zA-Z0-9-]+:lambda:[a-zA-Z0-9-]+:\d{12}:layer:[a-zA-Z0-9-_]+)|[a-zA-Z0-9-_]+` - - ** [VersionNumber](#API_DeleteLayerVersion_RequestSyntax) ** -The version number\. - -## Request Body - -The request does not have a request body\. - -## Response Syntax - -``` -HTTP/1.1 204 -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body\. - -## Errors - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/DeleteLayerVersion) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/DeleteLayerVersion) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/DeleteLayerVersion) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/DeleteLayerVersion) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/DeleteLayerVersion) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/DeleteLayerVersion) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/DeleteLayerVersion) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/DeleteLayerVersion) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/DeleteLayerVersion) \ No newline at end of file diff --git a/doc_source/API_DeleteProvisionedConcurrencyConfig.md b/doc_source/API_DeleteProvisionedConcurrencyConfig.md deleted file mode 100644 index 37cf75d6..00000000 --- a/doc_source/API_DeleteProvisionedConcurrencyConfig.md +++ /dev/null @@ -1,78 +0,0 @@ -# DeleteProvisionedConcurrencyConfig - -Deletes the provisioned concurrency configuration for a function\. - -## Request Syntax - -``` -DELETE /2019-09-30/functions/FunctionName/provisioned-concurrency?Qualifier=Qualifier HTTP/1.1 -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [FunctionName](#API_DeleteProvisionedConcurrencyConfig_RequestSyntax) ** -The name of the Lambda function\. - -**Name formats** -+ **Function name** \- `my-function`\. -+ **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:my-function`\. -+ **Partial ARN** \- `123456789012:function:my-function`\. -The length constraint applies only to the full ARN\. If you specify only the function name, it is limited to 64 characters in length\. -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [Qualifier](#API_DeleteProvisionedConcurrencyConfig_RequestSyntax) ** -The version number or alias name\. -Length Constraints: Minimum length of 1\. Maximum length of 128\. -Pattern: `(|[a-zA-Z0-9$_-]+)` - -## Request Body - -The request does not have a request body\. - -## Response Syntax - -``` -HTTP/1.1 204 -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body\. - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceConflictException** -The resource already exists, or another operation is in progress\. -HTTP Status Code: 409 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/DeleteProvisionedConcurrencyConfig) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/DeleteProvisionedConcurrencyConfig) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/DeleteProvisionedConcurrencyConfig) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/DeleteProvisionedConcurrencyConfig) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/DeleteProvisionedConcurrencyConfig) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/DeleteProvisionedConcurrencyConfig) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/DeleteProvisionedConcurrencyConfig) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/DeleteProvisionedConcurrencyConfig) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/DeleteProvisionedConcurrencyConfig) \ No newline at end of file diff --git a/doc_source/API_DestinationConfig.md b/doc_source/API_DestinationConfig.md deleted file mode 100644 index 9230f2cb..00000000 --- a/doc_source/API_DestinationConfig.md +++ /dev/null @@ -1,23 +0,0 @@ -# DestinationConfig - -A configuration object that specifies the destination of an event after Lambda processes it\. - -## Contents - - **OnFailure** -The destination configuration for failed invocations\. -Type: [OnFailure](API_OnFailure.md) object -Required: No - - **OnSuccess** -The destination configuration for successful invocations\. -Type: [OnSuccess](API_OnSuccess.md) object -Required: No - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/DestinationConfig) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/DestinationConfig) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/DestinationConfig) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/DestinationConfig) \ No newline at end of file diff --git a/doc_source/API_Environment.md b/doc_source/API_Environment.md deleted file mode 100644 index 9e140772..00000000 --- a/doc_source/API_Environment.md +++ /dev/null @@ -1,19 +0,0 @@ -# Environment - -A function's environment variable settings\. - -## Contents - - **Variables** -Environment variable key\-value pairs\. -Type: String to string map -Key Pattern: `[a-zA-Z]([a-zA-Z0-9_])+` -Required: No - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/Environment) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/Environment) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/Environment) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/Environment) \ No newline at end of file diff --git a/doc_source/API_EnvironmentError.md b/doc_source/API_EnvironmentError.md deleted file mode 100644 index 58d1e16f..00000000 --- a/doc_source/API_EnvironmentError.md +++ /dev/null @@ -1,23 +0,0 @@ -# EnvironmentError - -Error messages for environment variables that couldn't be applied\. - -## Contents - - **ErrorCode** -The error code\. -Type: String -Required: No - - **Message** -The error message\. -Type: String -Required: No - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/EnvironmentError) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/EnvironmentError) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/EnvironmentError) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/EnvironmentError) \ No newline at end of file diff --git a/doc_source/API_EnvironmentResponse.md b/doc_source/API_EnvironmentResponse.md deleted file mode 100644 index 625bfee0..00000000 --- a/doc_source/API_EnvironmentResponse.md +++ /dev/null @@ -1,24 +0,0 @@ -# EnvironmentResponse - -The results of an operation to update or read environment variables\. If the operation is successful, the response contains the environment variables\. If it failed, the response contains details about the error\. - -## Contents - - **Error** -Error messages for environment variables that couldn't be applied\. -Type: [EnvironmentError](API_EnvironmentError.md) object -Required: No - - **Variables** -Environment variable key\-value pairs\. -Type: String to string map -Key Pattern: `[a-zA-Z]([a-zA-Z0-9_])+` -Required: No - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/EnvironmentResponse) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/EnvironmentResponse) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/EnvironmentResponse) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/EnvironmentResponse) \ No newline at end of file diff --git a/doc_source/API_EventSourceMappingConfiguration.md b/doc_source/API_EventSourceMappingConfiguration.md deleted file mode 100644 index f3682266..00000000 --- a/doc_source/API_EventSourceMappingConfiguration.md +++ /dev/null @@ -1,90 +0,0 @@ -# EventSourceMappingConfiguration - -A mapping between an AWS resource and an AWS Lambda function\. See [CreateEventSourceMapping](API_CreateEventSourceMapping.md) for details\. - -## Contents - - **BatchSize** -The maximum number of items to retrieve in a single batch\. -Type: Integer -Valid Range: Minimum value of 1\. Maximum value of 10000\. -Required: No - - **BisectBatchOnFunctionError** -\(Streams\) If the function returns an error, split the batch in two and retry\. -Type: Boolean -Required: No - - **DestinationConfig** -\(Streams\) An Amazon SQS queue or Amazon SNS topic destination for discarded records\. -Type: [DestinationConfig](API_DestinationConfig.md) object -Required: No - - **EventSourceArn** -The Amazon Resource Name \(ARN\) of the event source\. -Type: String -Pattern: `arn:(aws[a-zA-Z0-9-]*):([a-zA-Z0-9\-])+:([a-z]{2}(-gov)?-[a-z]+-\d{1})?:(\d{12})?:(.*)` -Required: No - - **FunctionArn** -The ARN of the Lambda function\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}(-gov)?-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?` -Required: No - - **LastModified** -The date that the event source mapping was last updated, or its state changed, in Unix time seconds\. -Type: Timestamp -Required: No - - **LastProcessingResult** -The result of the last AWS Lambda invocation of your Lambda function\. -Type: String -Required: No - - **MaximumBatchingWindowInSeconds** -\(Streams\) The maximum amount of time to gather records before invoking the function, in seconds\. -Type: Integer -Valid Range: Minimum value of 0\. Maximum value of 300\. -Required: No - - **MaximumRecordAgeInSeconds** -\(Streams\) The maximum age of a record that Lambda sends to a function for processing\. -Type: Integer -Valid Range: Minimum value of 60\. Maximum value of 604800\. -Required: No - - **MaximumRetryAttempts** -\(Streams\) The maximum number of times to retry when the function returns an error\. -Type: Integer -Valid Range: Minimum value of 0\. Maximum value of 10000\. -Required: No - - **ParallelizationFactor** -\(Streams\) The number of batches to process from each shard concurrently\. -Type: Integer -Valid Range: Minimum value of 1\. Maximum value of 10\. -Required: No - - **State** -The state of the event source mapping\. It can be one of the following: `Creating`, `Enabling`, `Enabled`, `Disabling`, `Disabled`, `Updating`, or `Deleting`\. -Type: String -Required: No - - **StateTransitionReason** -Indicates whether the last change to the event source mapping was made by a user, or by the Lambda service\. -Type: String -Required: No - - **UUID** -The identifier of the event source mapping\. -Type: String -Required: No - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/EventSourceMappingConfiguration) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/EventSourceMappingConfiguration) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/EventSourceMappingConfiguration) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/EventSourceMappingConfiguration) \ No newline at end of file diff --git a/doc_source/API_FunctionCode.md b/doc_source/API_FunctionCode.md deleted file mode 100644 index 8487a2d7..00000000 --- a/doc_source/API_FunctionCode.md +++ /dev/null @@ -1,37 +0,0 @@ -# FunctionCode - -The code for the Lambda function\. You can specify either an object in Amazon S3, or upload a deployment package directly\. - -## Contents - - **S3Bucket** -An Amazon S3 bucket in the same AWS Region as your function\. The bucket can be in a different AWS account\. -Type: String -Length Constraints: Minimum length of 3\. Maximum length of 63\. -Pattern: `^[0-9A-Za-z\.\-_]*(? -The Amazon S3 key of the deployment package\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 1024\. -Required: No - - **S3ObjectVersion** -For versioned objects, the version of the deployment package object to use\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 1024\. -Required: No - - **ZipFile** -The base64\-encoded contents of the deployment package\. AWS SDK and AWS CLI clients handle the encoding for you\. -Type: Base64\-encoded binary data object -Required: No - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/FunctionCode) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/FunctionCode) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/FunctionCode) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/FunctionCode) \ No newline at end of file diff --git a/doc_source/API_FunctionCodeLocation.md b/doc_source/API_FunctionCodeLocation.md deleted file mode 100644 index 850b4594..00000000 --- a/doc_source/API_FunctionCodeLocation.md +++ /dev/null @@ -1,23 +0,0 @@ -# FunctionCodeLocation - -Details about a function's deployment package\. - -## Contents - - **Location** -A presigned URL that you can use to download the deployment package\. -Type: String -Required: No - - **RepositoryType** -The service that's hosting the file\. -Type: String -Required: No - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/FunctionCodeLocation) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/FunctionCodeLocation) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/FunctionCodeLocation) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/FunctionCodeLocation) \ No newline at end of file diff --git a/doc_source/API_FunctionConfiguration.md b/doc_source/API_FunctionConfiguration.md deleted file mode 100644 index a903b503..00000000 --- a/doc_source/API_FunctionConfiguration.md +++ /dev/null @@ -1,161 +0,0 @@ -# FunctionConfiguration - -Details about a function's configuration\. - -## Contents - - **CodeSha256** -The SHA256 hash of the function's deployment package\. -Type: String -Required: No - - **CodeSize** -The size of the function's deployment package, in bytes\. -Type: Long -Required: No - - **DeadLetterConfig** -The function's dead letter queue\. -Type: [DeadLetterConfig](API_DeadLetterConfig.md) object -Required: No - - **Description** -The function's description\. -Type: String -Length Constraints: Minimum length of 0\. Maximum length of 256\. -Required: No - - **Environment** -The function's environment variables\. -Type: [EnvironmentResponse](API_EnvironmentResponse.md) object -Required: No - - **FunctionArn** -The function's Amazon Resource Name \(ARN\)\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}(-gov)?-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_\.]+(:(\$LATEST|[a-zA-Z0-9-_]+))?` -Required: No - - **FunctionName** -The name of the function\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 170\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_\.]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` -Required: No - - **Handler** -The function that Lambda calls to begin executing your function\. -Type: String -Length Constraints: Maximum length of 128\. -Pattern: `[^\s]+` -Required: No - - **KMSKeyArn** -The KMS key that's used to encrypt the function's environment variables\. This key is only returned if you've configured a customer managed CMK\. -Type: String -Pattern: `(arn:(aws[a-zA-Z-]*)?:[a-z0-9-.]+:.*)|()` -Required: No - - **LastModified** -The date and time that the function was last updated, in [ISO\-8601 format](https://www.w3.org/TR/NOTE-datetime) \(YYYY\-MM\-DDThh:mm:ss\.sTZD\)\. -Type: String -Required: No - - **LastUpdateStatus** -The status of the last update that was performed on the function\. This is first set to `Successful` after function creation completes\. -Type: String -Valid Values:` Successful | Failed | InProgress` -Required: No - - **LastUpdateStatusReason** -The reason for the last update that was performed on the function\. -Type: String -Required: No - - **LastUpdateStatusReasonCode** -The reason code for the last update that was performed on the function\. -Type: String -Valid Values:` EniLimitExceeded | InsufficientRolePermissions | InvalidConfiguration | InternalError | SubnetOutOfIPAddresses | InvalidSubnet | InvalidSecurityGroup` -Required: No - - **Layers** -The function's [ layers](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)\. -Type: Array of [Layer](API_Layer.md) objects -Required: No - - **MasterArn** -For Lambda@Edge functions, the ARN of the master function\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}(-gov)?-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?` -Required: No - - **MemorySize** -The memory that's allocated to the function\. -Type: Integer -Valid Range: Minimum value of 128\. Maximum value of 3008\. -Required: No - - **RevisionId** -The latest updated revision of the function or alias\. -Type: String -Required: No - - **Role** -The function's execution role\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:iam::\d{12}:role/?[a-zA-Z_0-9+=,.@\-_/]+` -Required: No - - **Runtime** -The runtime environment for the Lambda function\. -Type: String -Valid Values:` nodejs10.x | nodejs12.x | java8 | java11 | python2.7 | python3.6 | python3.7 | python3.8 | dotnetcore2.1 | go1.x | ruby2.5 | ruby2.7 | provided` -Required: No - - **State** -The current state of the function\. When the state is `Inactive`, you can reactivate the function by invoking it\. -Type: String -Valid Values:` Pending | Active | Inactive | Failed` -Required: No - - **StateReason** -The reason for the function's current state\. -Type: String -Required: No - - **StateReasonCode** -The reason code for the function's current state\. When the code is `Creating`, you can't invoke or modify the function\. -Type: String -Valid Values:` Idle | Creating | Restoring | EniLimitExceeded | InsufficientRolePermissions | InvalidConfiguration | InternalError | SubnetOutOfIPAddresses | InvalidSubnet | InvalidSecurityGroup` -Required: No - - **Timeout** -The amount of time that Lambda allows a function to run before stopping it\. -Type: Integer -Valid Range: Minimum value of 1\. -Required: No - - **TracingConfig** -The function's AWS X\-Ray tracing configuration\. -Type: [TracingConfigResponse](API_TracingConfigResponse.md) object -Required: No - - **Version** -The version of the Lambda function\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 1024\. -Pattern: `(\$LATEST|[0-9]+)` -Required: No - - **VpcConfig** -The function's networking configuration\. -Type: [VpcConfigResponse](API_VpcConfigResponse.md) object -Required: No - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/FunctionConfiguration) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/FunctionConfiguration) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/FunctionConfiguration) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/FunctionConfiguration) \ No newline at end of file diff --git a/doc_source/API_FunctionEventInvokeConfig.md b/doc_source/API_FunctionEventInvokeConfig.md deleted file mode 100644 index e4236102..00000000 --- a/doc_source/API_FunctionEventInvokeConfig.md +++ /dev/null @@ -1,45 +0,0 @@ -# FunctionEventInvokeConfig - -## Contents - - **DestinationConfig** -A destination for events after they have been sent to a function for processing\. - -**Destinations** -+ **Function** \- The Amazon Resource Name \(ARN\) of a Lambda function\. -+ **Queue** \- The ARN of an SQS queue\. -+ **Topic** \- The ARN of an SNS topic\. -+ **Event Bus** \- The ARN of an Amazon EventBridge event bus\. -Type: [DestinationConfig](API_DestinationConfig.md) object -Required: No - - **FunctionArn** -The Amazon Resource Name \(ARN\) of the function\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}(-gov)?-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?` -Required: No - - **LastModified** -The date and time that the configuration was last updated, in Unix time seconds\. -Type: Timestamp -Required: No - - **MaximumEventAgeInSeconds** -The maximum age of a request that Lambda sends to a function for processing\. -Type: Integer -Valid Range: Minimum value of 60\. Maximum value of 21600\. -Required: No - - **MaximumRetryAttempts** -The maximum number of times to retry when the function returns an error\. -Type: Integer -Valid Range: Minimum value of 0\. Maximum value of 2\. -Required: No - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/FunctionEventInvokeConfig) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/FunctionEventInvokeConfig) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/FunctionEventInvokeConfig) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/FunctionEventInvokeConfig) \ No newline at end of file diff --git a/doc_source/API_GetAccountSettings.md b/doc_source/API_GetAccountSettings.md deleted file mode 100644 index 66703fc2..00000000 --- a/doc_source/API_GetAccountSettings.md +++ /dev/null @@ -1,75 +0,0 @@ -# GetAccountSettings - -Retrieves details about your account's [limits](https://docs.aws.amazon.com/lambda/latest/dg/limits.html) and usage in an AWS Region\. - -## Request Syntax - -``` -GET /2016-08-19/account-settings/ HTTP/1.1 -``` - -## URI Request Parameters - -The request does not use any URI parameters\. - -## Request Body - -The request does not have a request body\. - -## Response Syntax - -``` -HTTP/1.1 200 -Content-type: application/json - -{ - "[AccountLimit](#SSS-GetAccountSettings-response-AccountLimit)": { - "[CodeSizeUnzipped](API_AccountLimit.md#SSS-Type-AccountLimit-CodeSizeUnzipped)": number, - "[CodeSizeZipped](API_AccountLimit.md#SSS-Type-AccountLimit-CodeSizeZipped)": number, - "[ConcurrentExecutions](API_AccountLimit.md#SSS-Type-AccountLimit-ConcurrentExecutions)": number, - "[TotalCodeSize](API_AccountLimit.md#SSS-Type-AccountLimit-TotalCodeSize)": number, - "[UnreservedConcurrentExecutions](API_AccountLimit.md#SSS-Type-AccountLimit-UnreservedConcurrentExecutions)": number - }, - "[AccountUsage](#SSS-GetAccountSettings-response-AccountUsage)": { - "[FunctionCount](API_AccountUsage.md#SSS-Type-AccountUsage-FunctionCount)": number, - "[TotalCodeSize](API_AccountUsage.md#SSS-Type-AccountUsage-TotalCodeSize)": number - } -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 200 response\. - -The following data is returned in JSON format by the service\. - - ** [AccountLimit](#API_GetAccountSettings_ResponseSyntax) ** -Limits that are related to concurrency and code storage\. -Type: [AccountLimit](API_AccountLimit.md) object - - ** [AccountUsage](#API_GetAccountSettings_ResponseSyntax) ** -The number of functions and amount of storage in use\. -Type: [AccountUsage](API_AccountUsage.md) object - -## Errors - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/GetAccountSettings) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/GetAccountSettings) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/GetAccountSettings) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/GetAccountSettings) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/GetAccountSettings) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/GetAccountSettings) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/GetAccountSettings) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/GetAccountSettings) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/GetAccountSettings) \ No newline at end of file diff --git a/doc_source/API_GetAlias.md b/doc_source/API_GetAlias.md deleted file mode 100644 index cea3b081..00000000 --- a/doc_source/API_GetAlias.md +++ /dev/null @@ -1,120 +0,0 @@ -# GetAlias - -Returns details about a Lambda function [alias](https://docs.aws.amazon.com/lambda/latest/dg/versioning-aliases.html)\. - -## Request Syntax - -``` -GET /2015-03-31/functions/FunctionName/aliases/Name HTTP/1.1 -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [FunctionName](#API_GetAlias_RequestSyntax) ** -The name of the Lambda function\. - -**Name formats** -+ **Function name** \- `MyFunction`\. -+ **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:MyFunction`\. -+ **Partial ARN** \- `123456789012:function:MyFunction`\. -The length constraint applies only to the full ARN\. If you specify only the function name, it is limited to 64 characters in length\. -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [Name](#API_GetAlias_RequestSyntax) ** -The name of the alias\. -Length Constraints: Minimum length of 1\. Maximum length of 128\. -Pattern: `(?!^[0-9]+$)([a-zA-Z0-9-_]+)` - -## Request Body - -The request does not have a request body\. - -## Response Syntax - -``` -HTTP/1.1 200 -Content-type: application/json - -{ - "[AliasArn](#SSS-GetAlias-response-AliasArn)": "string", - "[Description](#SSS-GetAlias-response-Description)": "string", - "[FunctionVersion](#SSS-GetAlias-response-FunctionVersion)": "string", - "[Name](#SSS-GetAlias-response-Name)": "string", - "[RevisionId](#SSS-GetAlias-response-RevisionId)": "string", - "[RoutingConfig](#SSS-GetAlias-response-RoutingConfig)": { - "[AdditionalVersionWeights](API_AliasRoutingConfiguration.md#SSS-Type-AliasRoutingConfiguration-AdditionalVersionWeights)": { - "string" : number - } - } -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 200 response\. - -The following data is returned in JSON format by the service\. - - ** [AliasArn](#API_GetAlias_ResponseSyntax) ** -The Amazon Resource Name \(ARN\) of the alias\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}(-gov)?-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [Description](#API_GetAlias_ResponseSyntax) ** -A description of the alias\. -Type: String -Length Constraints: Minimum length of 0\. Maximum length of 256\. - - ** [FunctionVersion](#API_GetAlias_ResponseSyntax) ** -The function version that the alias invokes\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 1024\. -Pattern: `(\$LATEST|[0-9]+)` - - ** [Name](#API_GetAlias_ResponseSyntax) ** -The name of the alias\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 128\. -Pattern: `(?!^[0-9]+$)([a-zA-Z0-9-_]+)` - - ** [RevisionId](#API_GetAlias_ResponseSyntax) ** -A unique identifier that changes when you update the alias\. -Type: String - - ** [RoutingConfig](#API_GetAlias_ResponseSyntax) ** -The [routing configuration](https://docs.aws.amazon.com/lambda/latest/dg/lambda-traffic-shifting-using-aliases.html) of the alias\. -Type: [AliasRoutingConfiguration](API_AliasRoutingConfiguration.md) object - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/GetAlias) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/GetAlias) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/GetAlias) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/GetAlias) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/GetAlias) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/GetAlias) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/GetAlias) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/GetAlias) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/GetAlias) \ No newline at end of file diff --git a/doc_source/API_GetEventSourceMapping.md b/doc_source/API_GetEventSourceMapping.md deleted file mode 100644 index 15164e1b..00000000 --- a/doc_source/API_GetEventSourceMapping.md +++ /dev/null @@ -1,151 +0,0 @@ -# GetEventSourceMapping - -Returns details about an event source mapping\. You can get the identifier of a mapping from the output of [ListEventSourceMappings](API_ListEventSourceMappings.md)\. - -## Request Syntax - -``` -GET /2015-03-31/event-source-mappings/UUID HTTP/1.1 -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [UUID](#API_GetEventSourceMapping_RequestSyntax) ** -The identifier of the event source mapping\. - -## Request Body - -The request does not have a request body\. - -## Response Syntax - -``` -HTTP/1.1 200 -Content-type: application/json - -{ - "[BatchSize](#SSS-GetEventSourceMapping-response-BatchSize)": number, - "[BisectBatchOnFunctionError](#SSS-GetEventSourceMapping-response-BisectBatchOnFunctionError)": boolean, - "[DestinationConfig](#SSS-GetEventSourceMapping-response-DestinationConfig)": { - "[OnFailure](API_DestinationConfig.md#SSS-Type-DestinationConfig-OnFailure)": { - "[Destination](API_OnFailure.md#SSS-Type-OnFailure-Destination)": "string" - }, - "[OnSuccess](API_DestinationConfig.md#SSS-Type-DestinationConfig-OnSuccess)": { - "[Destination](API_OnSuccess.md#SSS-Type-OnSuccess-Destination)": "string" - } - }, - "[EventSourceArn](#SSS-GetEventSourceMapping-response-EventSourceArn)": "string", - "[FunctionArn](#SSS-GetEventSourceMapping-response-FunctionArn)": "string", - "[LastModified](#SSS-GetEventSourceMapping-response-LastModified)": number, - "[LastProcessingResult](#SSS-GetEventSourceMapping-response-LastProcessingResult)": "string", - "[MaximumBatchingWindowInSeconds](#SSS-GetEventSourceMapping-response-MaximumBatchingWindowInSeconds)": number, - "[MaximumRecordAgeInSeconds](#SSS-GetEventSourceMapping-response-MaximumRecordAgeInSeconds)": number, - "[MaximumRetryAttempts](#SSS-GetEventSourceMapping-response-MaximumRetryAttempts)": number, - "[ParallelizationFactor](#SSS-GetEventSourceMapping-response-ParallelizationFactor)": number, - "[State](#SSS-GetEventSourceMapping-response-State)": "string", - "[StateTransitionReason](#SSS-GetEventSourceMapping-response-StateTransitionReason)": "string", - "[UUID](#SSS-GetEventSourceMapping-response-UUID)": "string" -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 200 response\. - -The following data is returned in JSON format by the service\. - - ** [BatchSize](#API_GetEventSourceMapping_ResponseSyntax) ** -The maximum number of items to retrieve in a single batch\. -Type: Integer -Valid Range: Minimum value of 1\. Maximum value of 10000\. - - ** [BisectBatchOnFunctionError](#API_GetEventSourceMapping_ResponseSyntax) ** -\(Streams\) If the function returns an error, split the batch in two and retry\. -Type: Boolean - - ** [DestinationConfig](#API_GetEventSourceMapping_ResponseSyntax) ** -\(Streams\) An Amazon SQS queue or Amazon SNS topic destination for discarded records\. -Type: [DestinationConfig](API_DestinationConfig.md) object - - ** [EventSourceArn](#API_GetEventSourceMapping_ResponseSyntax) ** -The Amazon Resource Name \(ARN\) of the event source\. -Type: String -Pattern: `arn:(aws[a-zA-Z0-9-]*):([a-zA-Z0-9\-])+:([a-z]{2}(-gov)?-[a-z]+-\d{1})?:(\d{12})?:(.*)` - - ** [FunctionArn](#API_GetEventSourceMapping_ResponseSyntax) ** -The ARN of the Lambda function\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}(-gov)?-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [LastModified](#API_GetEventSourceMapping_ResponseSyntax) ** -The date that the event source mapping was last updated, or its state changed, in Unix time seconds\. -Type: Timestamp - - ** [LastProcessingResult](#API_GetEventSourceMapping_ResponseSyntax) ** -The result of the last AWS Lambda invocation of your Lambda function\. -Type: String - - ** [MaximumBatchingWindowInSeconds](#API_GetEventSourceMapping_ResponseSyntax) ** -\(Streams\) The maximum amount of time to gather records before invoking the function, in seconds\. -Type: Integer -Valid Range: Minimum value of 0\. Maximum value of 300\. - - ** [MaximumRecordAgeInSeconds](#API_GetEventSourceMapping_ResponseSyntax) ** -\(Streams\) The maximum age of a record that Lambda sends to a function for processing\. -Type: Integer -Valid Range: Minimum value of 60\. Maximum value of 604800\. - - ** [MaximumRetryAttempts](#API_GetEventSourceMapping_ResponseSyntax) ** -\(Streams\) The maximum number of times to retry when the function returns an error\. -Type: Integer -Valid Range: Minimum value of 0\. Maximum value of 10000\. - - ** [ParallelizationFactor](#API_GetEventSourceMapping_ResponseSyntax) ** -\(Streams\) The number of batches to process from each shard concurrently\. -Type: Integer -Valid Range: Minimum value of 1\. Maximum value of 10\. - - ** [State](#API_GetEventSourceMapping_ResponseSyntax) ** -The state of the event source mapping\. It can be one of the following: `Creating`, `Enabling`, `Enabled`, `Disabling`, `Disabled`, `Updating`, or `Deleting`\. -Type: String - - ** [StateTransitionReason](#API_GetEventSourceMapping_ResponseSyntax) ** -Indicates whether the last change to the event source mapping was made by a user, or by the Lambda service\. -Type: String - - ** [UUID](#API_GetEventSourceMapping_ResponseSyntax) ** -The identifier of the event source mapping\. -Type: String - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/GetEventSourceMapping) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/GetEventSourceMapping) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/GetEventSourceMapping) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/GetEventSourceMapping) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/GetEventSourceMapping) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/GetEventSourceMapping) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/GetEventSourceMapping) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/GetEventSourceMapping) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/GetEventSourceMapping) \ No newline at end of file diff --git a/doc_source/API_GetFunction.md b/doc_source/API_GetFunction.md deleted file mode 100644 index e9314123..00000000 --- a/doc_source/API_GetFunction.md +++ /dev/null @@ -1,155 +0,0 @@ -# GetFunction - -Returns information about the function or function version, with a link to download the deployment package that's valid for 10 minutes\. If you specify a function version, only details that are specific to that version are returned\. - -## Request Syntax - -``` -GET /2015-03-31/functions/FunctionName?Qualifier=Qualifier HTTP/1.1 -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [FunctionName](#API_GetFunction_RequestSyntax) ** -The name of the Lambda function, version, or alias\. - -**Name formats** -+ **Function name** \- `my-function` \(name\-only\), `my-function:v1` \(with alias\)\. -+ **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:my-function`\. -+ **Partial ARN** \- `123456789012:function:my-function`\. -You can append a version number or alias to any of the formats\. The length constraint applies only to the full ARN\. If you specify only the function name, it is limited to 64 characters in length\. -Length Constraints: Minimum length of 1\. Maximum length of 170\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_\.]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [Qualifier](#API_GetFunction_RequestSyntax) ** -Specify a version or alias to get details about a published version of the function\. -Length Constraints: Minimum length of 1\. Maximum length of 128\. -Pattern: `(|[a-zA-Z0-9$_-]+)` - -## Request Body - -The request does not have a request body\. - -## Response Syntax - -``` -HTTP/1.1 200 -Content-type: application/json - -{ - "[Code](#SSS-GetFunction-response-Code)": { - "[Location](API_FunctionCodeLocation.md#SSS-Type-FunctionCodeLocation-Location)": "string", - "[RepositoryType](API_FunctionCodeLocation.md#SSS-Type-FunctionCodeLocation-RepositoryType)": "string" - }, - "[Concurrency](#SSS-GetFunction-response-Concurrency)": { - "[ReservedConcurrentExecutions](API_Concurrency.md#SSS-Type-Concurrency-ReservedConcurrentExecutions)": number - }, - "[Configuration](#SSS-GetFunction-response-Configuration)": { - "[CodeSha256](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-CodeSha256)": "string", - "[CodeSize](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-CodeSize)": number, - "[DeadLetterConfig](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-DeadLetterConfig)": { - "[TargetArn](API_DeadLetterConfig.md#SSS-Type-DeadLetterConfig-TargetArn)": "string" - }, - "[Description](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-Description)": "string", - "[Environment](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-Environment)": { - "[Error](API_EnvironmentResponse.md#SSS-Type-EnvironmentResponse-Error)": { - "[ErrorCode](API_EnvironmentError.md#SSS-Type-EnvironmentError-ErrorCode)": "string", - "[Message](API_EnvironmentError.md#SSS-Type-EnvironmentError-Message)": "string" - }, - "[Variables](API_EnvironmentResponse.md#SSS-Type-EnvironmentResponse-Variables)": { - "string" : "string" - } - }, - "[FunctionArn](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-FunctionArn)": "string", - "[FunctionName](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-FunctionName)": "string", - "[Handler](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-Handler)": "string", - "[KMSKeyArn](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-KMSKeyArn)": "string", - "[LastModified](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-LastModified)": "string", - "[LastUpdateStatus](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-LastUpdateStatus)": "string", - "[LastUpdateStatusReason](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-LastUpdateStatusReason)": "string", - "[LastUpdateStatusReasonCode](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-LastUpdateStatusReasonCode)": "string", - "[Layers](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-Layers)": [ - { - "[Arn](API_Layer.md#SSS-Type-Layer-Arn)": "string", - "[CodeSize](API_Layer.md#SSS-Type-Layer-CodeSize)": number - } - ], - "[MasterArn](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-MasterArn)": "string", - "[MemorySize](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-MemorySize)": number, - "[RevisionId](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-RevisionId)": "string", - "[Role](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-Role)": "string", - "[Runtime](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-Runtime)": "string", - "[State](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-State)": "string", - "[StateReason](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-StateReason)": "string", - "[StateReasonCode](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-StateReasonCode)": "string", - "[Timeout](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-Timeout)": number, - "[TracingConfig](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-TracingConfig)": { - "[Mode](API_TracingConfigResponse.md#SSS-Type-TracingConfigResponse-Mode)": "string" - }, - "[Version](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-Version)": "string", - "[VpcConfig](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-VpcConfig)": { - "[SecurityGroupIds](API_VpcConfigResponse.md#SSS-Type-VpcConfigResponse-SecurityGroupIds)": [ "string" ], - "[SubnetIds](API_VpcConfigResponse.md#SSS-Type-VpcConfigResponse-SubnetIds)": [ "string" ], - "[VpcId](API_VpcConfigResponse.md#SSS-Type-VpcConfigResponse-VpcId)": "string" - } - }, - "[Tags](#SSS-GetFunction-response-Tags)": { - "string" : "string" - } -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 200 response\. - -The following data is returned in JSON format by the service\. - - ** [Code](#API_GetFunction_ResponseSyntax) ** -The deployment package of the function or version\. -Type: [FunctionCodeLocation](API_FunctionCodeLocation.md) object - - ** [Concurrency](#API_GetFunction_ResponseSyntax) ** -The function's [reserved concurrency](https://docs.aws.amazon.com/lambda/latest/dg/concurrent-executions.html)\. -Type: [Concurrency](API_Concurrency.md) object - - ** [Configuration](#API_GetFunction_ResponseSyntax) ** -The configuration of the function or version\. -Type: [FunctionConfiguration](API_FunctionConfiguration.md) object - - ** [Tags](#API_GetFunction_ResponseSyntax) ** -The function's [tags](https://docs.aws.amazon.com/lambda/latest/dg/tagging.html)\. -Type: String to string map - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/GetFunction) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/GetFunction) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/GetFunction) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/GetFunction) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/GetFunction) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/GetFunction) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/GetFunction) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/GetFunction) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/GetFunction) \ No newline at end of file diff --git a/doc_source/API_GetFunctionConcurrency.md b/doc_source/API_GetFunctionConcurrency.md deleted file mode 100644 index c163edd6..00000000 --- a/doc_source/API_GetFunctionConcurrency.md +++ /dev/null @@ -1,81 +0,0 @@ -# GetFunctionConcurrency - -Returns details about the reserved concurrency configuration for a function\. To set a concurrency limit for a function, use [PutFunctionConcurrency](API_PutFunctionConcurrency.md)\. - -## Request Syntax - -``` -GET /2019-09-30/functions/FunctionName/concurrency HTTP/1.1 -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [FunctionName](#API_GetFunctionConcurrency_RequestSyntax) ** -The name of the Lambda function\. - -**Name formats** -+ **Function name** \- `my-function`\. -+ **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:my-function`\. -+ **Partial ARN** \- `123456789012:function:my-function`\. -The length constraint applies only to the full ARN\. If you specify only the function name, it is limited to 64 characters in length\. -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - -## Request Body - -The request does not have a request body\. - -## Response Syntax - -``` -HTTP/1.1 200 -Content-type: application/json - -{ - "[ReservedConcurrentExecutions](#SSS-GetFunctionConcurrency-response-ReservedConcurrentExecutions)": number -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 200 response\. - -The following data is returned in JSON format by the service\. - - ** [ReservedConcurrentExecutions](#API_GetFunctionConcurrency_ResponseSyntax) ** -The number of simultaneous executions that are reserved for the function\. -Type: Integer -Valid Range: Minimum value of 0\. - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/GetFunctionConcurrency) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/GetFunctionConcurrency) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/GetFunctionConcurrency) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/GetFunctionConcurrency) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/GetFunctionConcurrency) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/GetFunctionConcurrency) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/GetFunctionConcurrency) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/GetFunctionConcurrency) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/GetFunctionConcurrency) \ No newline at end of file diff --git a/doc_source/API_GetFunctionConfiguration.md b/doc_source/API_GetFunctionConfiguration.md deleted file mode 100644 index 43063204..00000000 --- a/doc_source/API_GetFunctionConfiguration.md +++ /dev/null @@ -1,251 +0,0 @@ -# GetFunctionConfiguration - -Returns the version\-specific settings of a Lambda function or version\. The output includes only options that can vary between versions of a function\. To modify these settings, use [UpdateFunctionConfiguration](API_UpdateFunctionConfiguration.md)\. - -To get all of a function's details, including function\-level settings, use [GetFunction](API_GetFunction.md)\. - -## Request Syntax - -``` -GET /2015-03-31/functions/FunctionName/configuration?Qualifier=Qualifier HTTP/1.1 -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [FunctionName](#API_GetFunctionConfiguration_RequestSyntax) ** -The name of the Lambda function, version, or alias\. - -**Name formats** -+ **Function name** \- `my-function` \(name\-only\), `my-function:v1` \(with alias\)\. -+ **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:my-function`\. -+ **Partial ARN** \- `123456789012:function:my-function`\. -You can append a version number or alias to any of the formats\. The length constraint applies only to the full ARN\. If you specify only the function name, it is limited to 64 characters in length\. -Length Constraints: Minimum length of 1\. Maximum length of 170\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_\.]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [Qualifier](#API_GetFunctionConfiguration_RequestSyntax) ** -Specify a version or alias to get details about a published version of the function\. -Length Constraints: Minimum length of 1\. Maximum length of 128\. -Pattern: `(|[a-zA-Z0-9$_-]+)` - -## Request Body - -The request does not have a request body\. - -## Response Syntax - -``` -HTTP/1.1 200 -Content-type: application/json - -{ - "[CodeSha256](#SSS-GetFunctionConfiguration-response-CodeSha256)": "string", - "[CodeSize](#SSS-GetFunctionConfiguration-response-CodeSize)": number, - "[DeadLetterConfig](#SSS-GetFunctionConfiguration-response-DeadLetterConfig)": { - "[TargetArn](API_DeadLetterConfig.md#SSS-Type-DeadLetterConfig-TargetArn)": "string" - }, - "[Description](#SSS-GetFunctionConfiguration-response-Description)": "string", - "[Environment](#SSS-GetFunctionConfiguration-response-Environment)": { - "[Error](API_EnvironmentResponse.md#SSS-Type-EnvironmentResponse-Error)": { - "[ErrorCode](API_EnvironmentError.md#SSS-Type-EnvironmentError-ErrorCode)": "string", - "[Message](API_EnvironmentError.md#SSS-Type-EnvironmentError-Message)": "string" - }, - "[Variables](API_EnvironmentResponse.md#SSS-Type-EnvironmentResponse-Variables)": { - "string" : "string" - } - }, - "[FunctionArn](#SSS-GetFunctionConfiguration-response-FunctionArn)": "string", - "[FunctionName](#SSS-GetFunctionConfiguration-response-FunctionName)": "string", - "[Handler](#SSS-GetFunctionConfiguration-response-Handler)": "string", - "[KMSKeyArn](#SSS-GetFunctionConfiguration-response-KMSKeyArn)": "string", - "[LastModified](#SSS-GetFunctionConfiguration-response-LastModified)": "string", - "[LastUpdateStatus](#SSS-GetFunctionConfiguration-response-LastUpdateStatus)": "string", - "[LastUpdateStatusReason](#SSS-GetFunctionConfiguration-response-LastUpdateStatusReason)": "string", - "[LastUpdateStatusReasonCode](#SSS-GetFunctionConfiguration-response-LastUpdateStatusReasonCode)": "string", - "[Layers](#SSS-GetFunctionConfiguration-response-Layers)": [ - { - "[Arn](API_Layer.md#SSS-Type-Layer-Arn)": "string", - "[CodeSize](API_Layer.md#SSS-Type-Layer-CodeSize)": number - } - ], - "[MasterArn](#SSS-GetFunctionConfiguration-response-MasterArn)": "string", - "[MemorySize](#SSS-GetFunctionConfiguration-response-MemorySize)": number, - "[RevisionId](#SSS-GetFunctionConfiguration-response-RevisionId)": "string", - "[Role](#SSS-GetFunctionConfiguration-response-Role)": "string", - "[Runtime](#SSS-GetFunctionConfiguration-response-Runtime)": "string", - "[State](#SSS-GetFunctionConfiguration-response-State)": "string", - "[StateReason](#SSS-GetFunctionConfiguration-response-StateReason)": "string", - "[StateReasonCode](#SSS-GetFunctionConfiguration-response-StateReasonCode)": "string", - "[Timeout](#SSS-GetFunctionConfiguration-response-Timeout)": number, - "[TracingConfig](#SSS-GetFunctionConfiguration-response-TracingConfig)": { - "[Mode](API_TracingConfigResponse.md#SSS-Type-TracingConfigResponse-Mode)": "string" - }, - "[Version](#SSS-GetFunctionConfiguration-response-Version)": "string", - "[VpcConfig](#SSS-GetFunctionConfiguration-response-VpcConfig)": { - "[SecurityGroupIds](API_VpcConfigResponse.md#SSS-Type-VpcConfigResponse-SecurityGroupIds)": [ "string" ], - "[SubnetIds](API_VpcConfigResponse.md#SSS-Type-VpcConfigResponse-SubnetIds)": [ "string" ], - "[VpcId](API_VpcConfigResponse.md#SSS-Type-VpcConfigResponse-VpcId)": "string" - } -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 200 response\. - -The following data is returned in JSON format by the service\. - - ** [CodeSha256](#API_GetFunctionConfiguration_ResponseSyntax) ** -The SHA256 hash of the function's deployment package\. -Type: String - - ** [CodeSize](#API_GetFunctionConfiguration_ResponseSyntax) ** -The size of the function's deployment package, in bytes\. -Type: Long - - ** [DeadLetterConfig](#API_GetFunctionConfiguration_ResponseSyntax) ** -The function's dead letter queue\. -Type: [DeadLetterConfig](API_DeadLetterConfig.md) object - - ** [Description](#API_GetFunctionConfiguration_ResponseSyntax) ** -The function's description\. -Type: String -Length Constraints: Minimum length of 0\. Maximum length of 256\. - - ** [Environment](#API_GetFunctionConfiguration_ResponseSyntax) ** -The function's environment variables\. -Type: [EnvironmentResponse](API_EnvironmentResponse.md) object - - ** [FunctionArn](#API_GetFunctionConfiguration_ResponseSyntax) ** -The function's Amazon Resource Name \(ARN\)\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}(-gov)?-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_\.]+(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [FunctionName](#API_GetFunctionConfiguration_ResponseSyntax) ** -The name of the function\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 170\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_\.]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [Handler](#API_GetFunctionConfiguration_ResponseSyntax) ** -The function that Lambda calls to begin executing your function\. -Type: String -Length Constraints: Maximum length of 128\. -Pattern: `[^\s]+` - - ** [KMSKeyArn](#API_GetFunctionConfiguration_ResponseSyntax) ** -The KMS key that's used to encrypt the function's environment variables\. This key is only returned if you've configured a customer managed CMK\. -Type: String -Pattern: `(arn:(aws[a-zA-Z-]*)?:[a-z0-9-.]+:.*)|()` - - ** [LastModified](#API_GetFunctionConfiguration_ResponseSyntax) ** -The date and time that the function was last updated, in [ISO\-8601 format](https://www.w3.org/TR/NOTE-datetime) \(YYYY\-MM\-DDThh:mm:ss\.sTZD\)\. -Type: String - - ** [LastUpdateStatus](#API_GetFunctionConfiguration_ResponseSyntax) ** -The status of the last update that was performed on the function\. This is first set to `Successful` after function creation completes\. -Type: String -Valid Values:` Successful | Failed | InProgress` - - ** [LastUpdateStatusReason](#API_GetFunctionConfiguration_ResponseSyntax) ** -The reason for the last update that was performed on the function\. -Type: String - - ** [LastUpdateStatusReasonCode](#API_GetFunctionConfiguration_ResponseSyntax) ** -The reason code for the last update that was performed on the function\. -Type: String -Valid Values:` EniLimitExceeded | InsufficientRolePermissions | InvalidConfiguration | InternalError | SubnetOutOfIPAddresses | InvalidSubnet | InvalidSecurityGroup` - - ** [Layers](#API_GetFunctionConfiguration_ResponseSyntax) ** -The function's [ layers](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)\. -Type: Array of [Layer](API_Layer.md) objects - - ** [MasterArn](#API_GetFunctionConfiguration_ResponseSyntax) ** -For Lambda@Edge functions, the ARN of the master function\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}(-gov)?-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [MemorySize](#API_GetFunctionConfiguration_ResponseSyntax) ** -The memory that's allocated to the function\. -Type: Integer -Valid Range: Minimum value of 128\. Maximum value of 3008\. - - ** [RevisionId](#API_GetFunctionConfiguration_ResponseSyntax) ** -The latest updated revision of the function or alias\. -Type: String - - ** [Role](#API_GetFunctionConfiguration_ResponseSyntax) ** -The function's execution role\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:iam::\d{12}:role/?[a-zA-Z_0-9+=,.@\-_/]+` - - ** [Runtime](#API_GetFunctionConfiguration_ResponseSyntax) ** -The runtime environment for the Lambda function\. -Type: String -Valid Values:` nodejs10.x | nodejs12.x | java8 | java11 | python2.7 | python3.6 | python3.7 | python3.8 | dotnetcore2.1 | go1.x | ruby2.5 | ruby2.7 | provided` - - ** [State](#API_GetFunctionConfiguration_ResponseSyntax) ** -The current state of the function\. When the state is `Inactive`, you can reactivate the function by invoking it\. -Type: String -Valid Values:` Pending | Active | Inactive | Failed` - - ** [StateReason](#API_GetFunctionConfiguration_ResponseSyntax) ** -The reason for the function's current state\. -Type: String - - ** [StateReasonCode](#API_GetFunctionConfiguration_ResponseSyntax) ** -The reason code for the function's current state\. When the code is `Creating`, you can't invoke or modify the function\. -Type: String -Valid Values:` Idle | Creating | Restoring | EniLimitExceeded | InsufficientRolePermissions | InvalidConfiguration | InternalError | SubnetOutOfIPAddresses | InvalidSubnet | InvalidSecurityGroup` - - ** [Timeout](#API_GetFunctionConfiguration_ResponseSyntax) ** -The amount of time that Lambda allows a function to run before stopping it\. -Type: Integer -Valid Range: Minimum value of 1\. - - ** [TracingConfig](#API_GetFunctionConfiguration_ResponseSyntax) ** -The function's AWS X\-Ray tracing configuration\. -Type: [TracingConfigResponse](API_TracingConfigResponse.md) object - - ** [Version](#API_GetFunctionConfiguration_ResponseSyntax) ** -The version of the Lambda function\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 1024\. -Pattern: `(\$LATEST|[0-9]+)` - - ** [VpcConfig](#API_GetFunctionConfiguration_ResponseSyntax) ** -The function's networking configuration\. -Type: [VpcConfigResponse](API_VpcConfigResponse.md) object - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/GetFunctionConfiguration) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/GetFunctionConfiguration) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/GetFunctionConfiguration) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/GetFunctionConfiguration) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/GetFunctionConfiguration) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/GetFunctionConfiguration) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/GetFunctionConfiguration) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/GetFunctionConfiguration) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/GetFunctionConfiguration) \ No newline at end of file diff --git a/doc_source/API_GetFunctionEventInvokeConfig.md b/doc_source/API_GetFunctionEventInvokeConfig.md deleted file mode 100644 index 01668807..00000000 --- a/doc_source/API_GetFunctionEventInvokeConfig.md +++ /dev/null @@ -1,123 +0,0 @@ -# GetFunctionEventInvokeConfig - -Retrieves the configuration for asynchronous invocation for a function, version, or alias\. - -To configure options for asynchronous invocation, use [PutFunctionEventInvokeConfig](API_PutFunctionEventInvokeConfig.md)\. - -## Request Syntax - -``` -GET /2019-09-25/functions/FunctionName/event-invoke-config?Qualifier=Qualifier HTTP/1.1 -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [FunctionName](#API_GetFunctionEventInvokeConfig_RequestSyntax) ** -The name of the Lambda function, version, or alias\. - -**Name formats** -+ **Function name** \- `my-function` \(name\-only\), `my-function:v1` \(with alias\)\. -+ **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:my-function`\. -+ **Partial ARN** \- `123456789012:function:my-function`\. -You can append a version number or alias to any of the formats\. The length constraint applies only to the full ARN\. If you specify only the function name, it is limited to 64 characters in length\. -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [Qualifier](#API_GetFunctionEventInvokeConfig_RequestSyntax) ** -A version number or alias name\. -Length Constraints: Minimum length of 1\. Maximum length of 128\. -Pattern: `(|[a-zA-Z0-9$_-]+)` - -## Request Body - -The request does not have a request body\. - -## Response Syntax - -``` -HTTP/1.1 200 -Content-type: application/json - -{ - "[DestinationConfig](#SSS-GetFunctionEventInvokeConfig-response-DestinationConfig)": { - "[OnFailure](API_DestinationConfig.md#SSS-Type-DestinationConfig-OnFailure)": { - "[Destination](API_OnFailure.md#SSS-Type-OnFailure-Destination)": "string" - }, - "[OnSuccess](API_DestinationConfig.md#SSS-Type-DestinationConfig-OnSuccess)": { - "[Destination](API_OnSuccess.md#SSS-Type-OnSuccess-Destination)": "string" - } - }, - "[FunctionArn](#SSS-GetFunctionEventInvokeConfig-response-FunctionArn)": "string", - "[LastModified](#SSS-GetFunctionEventInvokeConfig-response-LastModified)": number, - "[MaximumEventAgeInSeconds](#SSS-GetFunctionEventInvokeConfig-response-MaximumEventAgeInSeconds)": number, - "[MaximumRetryAttempts](#SSS-GetFunctionEventInvokeConfig-response-MaximumRetryAttempts)": number -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 200 response\. - -The following data is returned in JSON format by the service\. - - ** [DestinationConfig](#API_GetFunctionEventInvokeConfig_ResponseSyntax) ** -A destination for events after they have been sent to a function for processing\. - -**Destinations** -+ **Function** \- The Amazon Resource Name \(ARN\) of a Lambda function\. -+ **Queue** \- The ARN of an SQS queue\. -+ **Topic** \- The ARN of an SNS topic\. -+ **Event Bus** \- The ARN of an Amazon EventBridge event bus\. -Type: [DestinationConfig](API_DestinationConfig.md) object - - ** [FunctionArn](#API_GetFunctionEventInvokeConfig_ResponseSyntax) ** -The Amazon Resource Name \(ARN\) of the function\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}(-gov)?-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [LastModified](#API_GetFunctionEventInvokeConfig_ResponseSyntax) ** -The date and time that the configuration was last updated, in Unix time seconds\. -Type: Timestamp - - ** [MaximumEventAgeInSeconds](#API_GetFunctionEventInvokeConfig_ResponseSyntax) ** -The maximum age of a request that Lambda sends to a function for processing\. -Type: Integer -Valid Range: Minimum value of 60\. Maximum value of 21600\. - - ** [MaximumRetryAttempts](#API_GetFunctionEventInvokeConfig_ResponseSyntax) ** -The maximum number of times to retry when the function returns an error\. -Type: Integer -Valid Range: Minimum value of 0\. Maximum value of 2\. - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/GetFunctionEventInvokeConfig) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/GetFunctionEventInvokeConfig) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/GetFunctionEventInvokeConfig) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/GetFunctionEventInvokeConfig) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/GetFunctionEventInvokeConfig) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/GetFunctionEventInvokeConfig) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/GetFunctionEventInvokeConfig) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/GetFunctionEventInvokeConfig) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/GetFunctionEventInvokeConfig) \ No newline at end of file diff --git a/doc_source/API_GetLayerVersion.md b/doc_source/API_GetLayerVersion.md deleted file mode 100644 index d0bad141..00000000 --- a/doc_source/API_GetLayerVersion.md +++ /dev/null @@ -1,124 +0,0 @@ -# GetLayerVersion - -Returns information about a version of an [AWS Lambda layer](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html), with a link to download the layer archive that's valid for 10 minutes\. - -## Request Syntax - -``` -GET /2018-10-31/layers/LayerName/versions/VersionNumber HTTP/1.1 -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [LayerName](#API_GetLayerVersion_RequestSyntax) ** -The name or Amazon Resource Name \(ARN\) of the layer\. -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:[a-zA-Z0-9-]+:lambda:[a-zA-Z0-9-]+:\d{12}:layer:[a-zA-Z0-9-_]+)|[a-zA-Z0-9-_]+` - - ** [VersionNumber](#API_GetLayerVersion_RequestSyntax) ** -The version number\. - -## Request Body - -The request does not have a request body\. - -## Response Syntax - -``` -HTTP/1.1 200 -Content-type: application/json - -{ - "[CompatibleRuntimes](#SSS-GetLayerVersion-response-CompatibleRuntimes)": [ "string" ], - "[Content](#SSS-GetLayerVersion-response-Content)": { - "[CodeSha256](API_LayerVersionContentOutput.md#SSS-Type-LayerVersionContentOutput-CodeSha256)": "string", - "[CodeSize](API_LayerVersionContentOutput.md#SSS-Type-LayerVersionContentOutput-CodeSize)": number, - "[Location](API_LayerVersionContentOutput.md#SSS-Type-LayerVersionContentOutput-Location)": "string" - }, - "[CreatedDate](#SSS-GetLayerVersion-response-CreatedDate)": "string", - "[Description](#SSS-GetLayerVersion-response-Description)": "string", - "[LayerArn](#SSS-GetLayerVersion-response-LayerArn)": "string", - "[LayerVersionArn](#SSS-GetLayerVersion-response-LayerVersionArn)": "string", - "[LicenseInfo](#SSS-GetLayerVersion-response-LicenseInfo)": "string", - "[Version](#SSS-GetLayerVersion-response-Version)": number -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 200 response\. - -The following data is returned in JSON format by the service\. - - ** [CompatibleRuntimes](#API_GetLayerVersion_ResponseSyntax) ** -The layer's compatible runtimes\. -Type: Array of strings -Array Members: Maximum number of 5 items\. -Valid Values:` nodejs10.x | nodejs12.x | java8 | java11 | python2.7 | python3.6 | python3.7 | python3.8 | dotnetcore2.1 | go1.x | ruby2.5 | ruby2.7 | provided` - - ** [Content](#API_GetLayerVersion_ResponseSyntax) ** -Details about the layer version\. -Type: [LayerVersionContentOutput](API_LayerVersionContentOutput.md) object - - ** [CreatedDate](#API_GetLayerVersion_ResponseSyntax) ** -The date that the layer version was created, in [ISO\-8601 format](https://www.w3.org/TR/NOTE-datetime) \(YYYY\-MM\-DDThh:mm:ss\.sTZD\)\. -Type: String - - ** [Description](#API_GetLayerVersion_ResponseSyntax) ** -The description of the version\. -Type: String -Length Constraints: Minimum length of 0\. Maximum length of 256\. - - ** [LayerArn](#API_GetLayerVersion_ResponseSyntax) ** -The ARN of the layer\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `arn:[a-zA-Z0-9-]+:lambda:[a-zA-Z0-9-]+:\d{12}:layer:[a-zA-Z0-9-_]+` - - ** [LayerVersionArn](#API_GetLayerVersion_ResponseSyntax) ** -The ARN of the layer version\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `arn:[a-zA-Z0-9-]+:lambda:[a-zA-Z0-9-]+:\d{12}:layer:[a-zA-Z0-9-_]+:[0-9]+` - - ** [LicenseInfo](#API_GetLayerVersion_ResponseSyntax) ** -The layer's software license\. -Type: String -Length Constraints: Maximum length of 512\. - - ** [Version](#API_GetLayerVersion_ResponseSyntax) ** -The version number\. -Type: Long - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/GetLayerVersion) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/GetLayerVersion) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/GetLayerVersion) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/GetLayerVersion) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/GetLayerVersion) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/GetLayerVersion) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/GetLayerVersion) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/GetLayerVersion) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/GetLayerVersion) \ No newline at end of file diff --git a/doc_source/API_GetLayerVersionByArn.md b/doc_source/API_GetLayerVersionByArn.md deleted file mode 100644 index 41216d31..00000000 --- a/doc_source/API_GetLayerVersionByArn.md +++ /dev/null @@ -1,121 +0,0 @@ -# GetLayerVersionByArn - -Returns information about a version of an [AWS Lambda layer](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html), with a link to download the layer archive that's valid for 10 minutes\. - -## Request Syntax - -``` -GET /2018-10-31/layers?find=LayerVersion&Arn=Arn HTTP/1.1 -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [Arn](#API_GetLayerVersionByArn_RequestSyntax) ** -The ARN of the layer version\. -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `arn:[a-zA-Z0-9-]+:lambda:[a-zA-Z0-9-]+:\d{12}:layer:[a-zA-Z0-9-_]+:[0-9]+` - -## Request Body - -The request does not have a request body\. - -## Response Syntax - -``` -HTTP/1.1 200 -Content-type: application/json - -{ - "[CompatibleRuntimes](#SSS-GetLayerVersionByArn-response-CompatibleRuntimes)": [ "string" ], - "[Content](#SSS-GetLayerVersionByArn-response-Content)": { - "[CodeSha256](API_LayerVersionContentOutput.md#SSS-Type-LayerVersionContentOutput-CodeSha256)": "string", - "[CodeSize](API_LayerVersionContentOutput.md#SSS-Type-LayerVersionContentOutput-CodeSize)": number, - "[Location](API_LayerVersionContentOutput.md#SSS-Type-LayerVersionContentOutput-Location)": "string" - }, - "[CreatedDate](#SSS-GetLayerVersionByArn-response-CreatedDate)": "string", - "[Description](#SSS-GetLayerVersionByArn-response-Description)": "string", - "[LayerArn](#SSS-GetLayerVersionByArn-response-LayerArn)": "string", - "[LayerVersionArn](#SSS-GetLayerVersionByArn-response-LayerVersionArn)": "string", - "[LicenseInfo](#SSS-GetLayerVersionByArn-response-LicenseInfo)": "string", - "[Version](#SSS-GetLayerVersionByArn-response-Version)": number -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 200 response\. - -The following data is returned in JSON format by the service\. - - ** [CompatibleRuntimes](#API_GetLayerVersionByArn_ResponseSyntax) ** -The layer's compatible runtimes\. -Type: Array of strings -Array Members: Maximum number of 5 items\. -Valid Values:` nodejs10.x | nodejs12.x | java8 | java11 | python2.7 | python3.6 | python3.7 | python3.8 | dotnetcore2.1 | go1.x | ruby2.5 | ruby2.7 | provided` - - ** [Content](#API_GetLayerVersionByArn_ResponseSyntax) ** -Details about the layer version\. -Type: [LayerVersionContentOutput](API_LayerVersionContentOutput.md) object - - ** [CreatedDate](#API_GetLayerVersionByArn_ResponseSyntax) ** -The date that the layer version was created, in [ISO\-8601 format](https://www.w3.org/TR/NOTE-datetime) \(YYYY\-MM\-DDThh:mm:ss\.sTZD\)\. -Type: String - - ** [Description](#API_GetLayerVersionByArn_ResponseSyntax) ** -The description of the version\. -Type: String -Length Constraints: Minimum length of 0\. Maximum length of 256\. - - ** [LayerArn](#API_GetLayerVersionByArn_ResponseSyntax) ** -The ARN of the layer\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `arn:[a-zA-Z0-9-]+:lambda:[a-zA-Z0-9-]+:\d{12}:layer:[a-zA-Z0-9-_]+` - - ** [LayerVersionArn](#API_GetLayerVersionByArn_ResponseSyntax) ** -The ARN of the layer version\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `arn:[a-zA-Z0-9-]+:lambda:[a-zA-Z0-9-]+:\d{12}:layer:[a-zA-Z0-9-_]+:[0-9]+` - - ** [LicenseInfo](#API_GetLayerVersionByArn_ResponseSyntax) ** -The layer's software license\. -Type: String -Length Constraints: Maximum length of 512\. - - ** [Version](#API_GetLayerVersionByArn_ResponseSyntax) ** -The version number\. -Type: Long - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/GetLayerVersionByArn) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/GetLayerVersionByArn) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/GetLayerVersionByArn) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/GetLayerVersionByArn) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/GetLayerVersionByArn) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/GetLayerVersionByArn) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/GetLayerVersionByArn) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/GetLayerVersionByArn) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/GetLayerVersionByArn) \ No newline at end of file diff --git a/doc_source/API_GetLayerVersionPolicy.md b/doc_source/API_GetLayerVersionPolicy.md deleted file mode 100644 index f52ecff3..00000000 --- a/doc_source/API_GetLayerVersionPolicy.md +++ /dev/null @@ -1,82 +0,0 @@ -# GetLayerVersionPolicy - -Returns the permission policy for a version of an [AWS Lambda layer](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)\. For more information, see [AddLayerVersionPermission](API_AddLayerVersionPermission.md)\. - -## Request Syntax - -``` -GET /2018-10-31/layers/LayerName/versions/VersionNumber/policy HTTP/1.1 -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [LayerName](#API_GetLayerVersionPolicy_RequestSyntax) ** -The name or Amazon Resource Name \(ARN\) of the layer\. -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:[a-zA-Z0-9-]+:lambda:[a-zA-Z0-9-]+:\d{12}:layer:[a-zA-Z0-9-_]+)|[a-zA-Z0-9-_]+` - - ** [VersionNumber](#API_GetLayerVersionPolicy_RequestSyntax) ** -The version number\. - -## Request Body - -The request does not have a request body\. - -## Response Syntax - -``` -HTTP/1.1 200 -Content-type: application/json - -{ - "[Policy](#SSS-GetLayerVersionPolicy-response-Policy)": "string", - "[RevisionId](#SSS-GetLayerVersionPolicy-response-RevisionId)": "string" -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 200 response\. - -The following data is returned in JSON format by the service\. - - ** [Policy](#API_GetLayerVersionPolicy_ResponseSyntax) ** -The policy document\. -Type: String - - ** [RevisionId](#API_GetLayerVersionPolicy_ResponseSyntax) ** -A unique identifier for the current revision of the policy\. -Type: String - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/GetLayerVersionPolicy) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/GetLayerVersionPolicy) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/GetLayerVersionPolicy) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/GetLayerVersionPolicy) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/GetLayerVersionPolicy) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/GetLayerVersionPolicy) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/GetLayerVersionPolicy) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/GetLayerVersionPolicy) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/GetLayerVersionPolicy) \ No newline at end of file diff --git a/doc_source/API_GetPolicy.md b/doc_source/API_GetPolicy.md deleted file mode 100644 index 3eae77f5..00000000 --- a/doc_source/API_GetPolicy.md +++ /dev/null @@ -1,90 +0,0 @@ -# GetPolicy - -Returns the [resource\-based IAM policy](https://docs.aws.amazon.com/lambda/latest/dg/access-control-resource-based.html) for a function, version, or alias\. - -## Request Syntax - -``` -GET /2015-03-31/functions/FunctionName/policy?Qualifier=Qualifier HTTP/1.1 -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [FunctionName](#API_GetPolicy_RequestSyntax) ** -The name of the Lambda function, version, or alias\. - -**Name formats** -+ **Function name** \- `my-function` \(name\-only\), `my-function:v1` \(with alias\)\. -+ **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:my-function`\. -+ **Partial ARN** \- `123456789012:function:my-function`\. -You can append a version number or alias to any of the formats\. The length constraint applies only to the full ARN\. If you specify only the function name, it is limited to 64 characters in length\. -Length Constraints: Minimum length of 1\. Maximum length of 170\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_\.]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [Qualifier](#API_GetPolicy_RequestSyntax) ** -Specify a version or alias to get the policy for that resource\. -Length Constraints: Minimum length of 1\. Maximum length of 128\. -Pattern: `(|[a-zA-Z0-9$_-]+)` - -## Request Body - -The request does not have a request body\. - -## Response Syntax - -``` -HTTP/1.1 200 -Content-type: application/json - -{ - "[Policy](#SSS-GetPolicy-response-Policy)": "string", - "[RevisionId](#SSS-GetPolicy-response-RevisionId)": "string" -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 200 response\. - -The following data is returned in JSON format by the service\. - - ** [Policy](#API_GetPolicy_ResponseSyntax) ** -The resource\-based policy\. -Type: String - - ** [RevisionId](#API_GetPolicy_ResponseSyntax) ** -A unique identifier for the current revision of the policy\. -Type: String - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/GetPolicy) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/GetPolicy) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/GetPolicy) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/GetPolicy) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/GetPolicy) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/GetPolicy) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/GetPolicy) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/GetPolicy) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/GetPolicy) \ No newline at end of file diff --git a/doc_source/API_GetProvisionedConcurrencyConfig.md b/doc_source/API_GetProvisionedConcurrencyConfig.md deleted file mode 100644 index 414a431d..00000000 --- a/doc_source/API_GetProvisionedConcurrencyConfig.md +++ /dev/null @@ -1,118 +0,0 @@ -# GetProvisionedConcurrencyConfig - -Retrieves the provisioned concurrency configuration for a function's alias or version\. - -## Request Syntax - -``` -GET /2019-09-30/functions/FunctionName/provisioned-concurrency?Qualifier=Qualifier HTTP/1.1 -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [FunctionName](#API_GetProvisionedConcurrencyConfig_RequestSyntax) ** -The name of the Lambda function\. - -**Name formats** -+ **Function name** \- `my-function`\. -+ **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:my-function`\. -+ **Partial ARN** \- `123456789012:function:my-function`\. -The length constraint applies only to the full ARN\. If you specify only the function name, it is limited to 64 characters in length\. -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [Qualifier](#API_GetProvisionedConcurrencyConfig_RequestSyntax) ** -The version number or alias name\. -Length Constraints: Minimum length of 1\. Maximum length of 128\. -Pattern: `(|[a-zA-Z0-9$_-]+)` - -## Request Body - -The request does not have a request body\. - -## Response Syntax - -``` -HTTP/1.1 200 -Content-type: application/json - -{ - "[AllocatedProvisionedConcurrentExecutions](#SSS-GetProvisionedConcurrencyConfig-response-AllocatedProvisionedConcurrentExecutions)": number, - "[AvailableProvisionedConcurrentExecutions](#SSS-GetProvisionedConcurrencyConfig-response-AvailableProvisionedConcurrentExecutions)": number, - "[LastModified](#SSS-GetProvisionedConcurrencyConfig-response-LastModified)": "string", - "[RequestedProvisionedConcurrentExecutions](#SSS-GetProvisionedConcurrencyConfig-response-RequestedProvisionedConcurrentExecutions)": number, - "[Status](#SSS-GetProvisionedConcurrencyConfig-response-Status)": "string", - "[StatusReason](#SSS-GetProvisionedConcurrencyConfig-response-StatusReason)": "string" -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 200 response\. - -The following data is returned in JSON format by the service\. - - ** [AllocatedProvisionedConcurrentExecutions](#API_GetProvisionedConcurrencyConfig_ResponseSyntax) ** -The amount of provisioned concurrency allocated\. -Type: Integer -Valid Range: Minimum value of 0\. - - ** [AvailableProvisionedConcurrentExecutions](#API_GetProvisionedConcurrencyConfig_ResponseSyntax) ** -The amount of provisioned concurrency available\. -Type: Integer -Valid Range: Minimum value of 0\. - - ** [LastModified](#API_GetProvisionedConcurrencyConfig_ResponseSyntax) ** -The date and time that a user last updated the configuration, in [ISO 8601 format](https://www.iso.org/iso-8601-date-and-time-format.html)\. -Type: String - - ** [RequestedProvisionedConcurrentExecutions](#API_GetProvisionedConcurrencyConfig_ResponseSyntax) ** -The amount of provisioned concurrency requested\. -Type: Integer -Valid Range: Minimum value of 1\. - - ** [Status](#API_GetProvisionedConcurrencyConfig_ResponseSyntax) ** -The status of the allocation process\. -Type: String -Valid Values:` IN_PROGRESS | READY | FAILED` - - ** [StatusReason](#API_GetProvisionedConcurrencyConfig_ResponseSyntax) ** -For failed allocations, the reason that provisioned concurrency could not be allocated\. -Type: String - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ProvisionedConcurrencyConfigNotFoundException** -The specified configuration does not exist\. -HTTP Status Code: 404 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/GetProvisionedConcurrencyConfig) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/GetProvisionedConcurrencyConfig) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/GetProvisionedConcurrencyConfig) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/GetProvisionedConcurrencyConfig) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/GetProvisionedConcurrencyConfig) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/GetProvisionedConcurrencyConfig) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/GetProvisionedConcurrencyConfig) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/GetProvisionedConcurrencyConfig) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/GetProvisionedConcurrencyConfig) \ No newline at end of file diff --git a/doc_source/API_Invoke.md b/doc_source/API_Invoke.md deleted file mode 100644 index f79d091f..00000000 --- a/doc_source/API_Invoke.md +++ /dev/null @@ -1,206 +0,0 @@ -# Invoke - -Invokes a Lambda function\. You can invoke a function synchronously \(and wait for the response\), or asynchronously\. To invoke a function asynchronously, set `InvocationType` to `Event`\. - -For [synchronous invocation](https://docs.aws.amazon.com/lambda/latest/dg/invocation-sync.html), details about the function response, including errors, are included in the response body and headers\. For either invocation type, you can find more information in the [execution log](https://docs.aws.amazon.com/lambda/latest/dg/monitoring-functions.html) and [trace](https://docs.aws.amazon.com/lambda/latest/dg/lambda-x-ray.html)\. - -When an error occurs, your function may be invoked multiple times\. Retry behavior varies by error type, client, event source, and invocation type\. For example, if you invoke a function asynchronously and it returns an error, Lambda executes the function up to two more times\. For more information, see [Retry Behavior](https://docs.aws.amazon.com/lambda/latest/dg/retries-on-errors.html)\. - -For [asynchronous invocation](https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html), Lambda adds events to a queue before sending them to your function\. If your function does not have enough capacity to keep up with the queue, events may be lost\. Occasionally, your function may receive the same event multiple times, even if no error occurs\. To retain events that were not processed, configure your function with a [dead\-letter queue](https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html#dlq)\. - -The status code in the API response doesn't reflect function errors\. Error codes are reserved for errors that prevent your function from executing, such as permissions errors, [limit errors](https://docs.aws.amazon.com/lambda/latest/dg/limits.html), or issues with your function's code and configuration\. For example, Lambda returns `TooManyRequestsException` if executing the function would cause you to exceed a concurrency limit at either the account level \(`ConcurrentInvocationLimitExceeded`\) or function level \(`ReservedFunctionConcurrentInvocationLimitExceeded`\)\. - -For functions with a long timeout, your client might be disconnected during synchronous invocation while it waits for a response\. Configure your HTTP client, SDK, firewall, proxy, or operating system to allow for long connections with timeout or keep\-alive settings\. - -This operation requires permission for the `lambda:InvokeFunction` action\. - -## Request Syntax - -``` -POST /2015-03-31/functions/FunctionName/invocations?Qualifier=Qualifier HTTP/1.1 -X-Amz-Invocation-Type: InvocationType -X-Amz-Log-Type: LogType -X-Amz-Client-Context: ClientContext - -Payload -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [ClientContext](#API_Invoke_RequestSyntax) ** -Up to 3583 bytes of base64\-encoded data about the invoking client to pass to the function in the context object\. - - ** [FunctionName](#API_Invoke_RequestSyntax) ** -The name of the Lambda function, version, or alias\. - -**Name formats** -+ **Function name** \- `my-function` \(name\-only\), `my-function:v1` \(with alias\)\. -+ **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:my-function`\. -+ **Partial ARN** \- `123456789012:function:my-function`\. -You can append a version number or alias to any of the formats\. The length constraint applies only to the full ARN\. If you specify only the function name, it is limited to 64 characters in length\. -Length Constraints: Minimum length of 1\. Maximum length of 170\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_\.]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [InvocationType](#API_Invoke_RequestSyntax) ** -Choose from the following options\. -+ `RequestResponse` \(default\) \- Invoke the function synchronously\. Keep the connection open until the function returns a response or times out\. The API response includes the function response and additional data\. -+ `Event` \- Invoke the function asynchronously\. Send events that fail multiple times to the function's dead\-letter queue \(if it's configured\)\. The API response only includes a status code\. -+ `DryRun` \- Validate parameter values and verify that the user or role has permission to invoke the function\. -Valid Values:` Event | RequestResponse | DryRun` - - ** [LogType](#API_Invoke_RequestSyntax) ** -Set to `Tail` to include the execution log in the response\. -Valid Values:` None | Tail` - - ** [Qualifier](#API_Invoke_RequestSyntax) ** -Specify a version or alias to invoke a published version of the function\. -Length Constraints: Minimum length of 1\. Maximum length of 128\. -Pattern: `(|[a-zA-Z0-9$_-]+)` - -## Request Body - -The request accepts the following binary data\. - - ** [Payload](#API_Invoke_RequestSyntax) ** -The JSON that you want to provide to your Lambda function as input\. - -## Response Syntax - -``` -HTTP/1.1 StatusCode -X-Amz-Function-Error: FunctionError -X-Amz-Log-Result: LogResult -X-Amz-Executed-Version: ExecutedVersion - -Payload -``` - -## Response Elements - -If the action is successful, the service sends back the following HTTP response\. - - ** [StatusCode](#API_Invoke_ResponseSyntax) ** -The HTTP status code is in the 200 range for a successful request\. For the `RequestResponse` invocation type, this status code is 200\. For the `Event` invocation type, this status code is 202\. For the `DryRun` invocation type, the status code is 204\. - -The response returns the following HTTP headers\. - - ** [ExecutedVersion](#API_Invoke_ResponseSyntax) ** -The version of the function that executed\. When you invoke a function with an alias, this indicates which version the alias resolved to\. -Length Constraints: Minimum length of 1\. Maximum length of 1024\. -Pattern: `(\$LATEST|[0-9]+)` - - ** [FunctionError](#API_Invoke_ResponseSyntax) ** -If present, indicates that an error occurred during function execution\. Details about the error are included in the response payload\. - - ** [LogResult](#API_Invoke_ResponseSyntax) ** -The last 4 KB of the execution log, which is base64 encoded\. - -The response returns the following as the HTTP body\. - - ** [Payload](#API_Invoke_ResponseSyntax) ** -The response from the function, or an error object\. - -## Errors - - **EC2AccessDeniedException** -Need additional permissions to configure VPC settings\. -HTTP Status Code: 502 - - **EC2ThrottledException** -AWS Lambda was throttled by Amazon EC2 during Lambda function initialization using the execution role provided for the Lambda function\. -HTTP Status Code: 502 - - **EC2UnexpectedException** -AWS Lambda received an unexpected EC2 client exception while setting up for the Lambda function\. -HTTP Status Code: 502 - - **ENILimitReachedException** -AWS Lambda was not able to create an elastic network interface in the VPC, specified as part of Lambda function configuration, because the limit for network interfaces has been reached\. -HTTP Status Code: 502 - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **InvalidRequestContentException** -The request body could not be parsed as JSON\. -HTTP Status Code: 400 - - **InvalidRuntimeException** -The runtime or runtime version specified is not supported\. -HTTP Status Code: 502 - - **InvalidSecurityGroupIDException** -The Security Group ID provided in the Lambda function VPC configuration is invalid\. -HTTP Status Code: 502 - - **InvalidSubnetIDException** -The Subnet ID provided in the Lambda function VPC configuration is invalid\. -HTTP Status Code: 502 - - **InvalidZipFileException** -AWS Lambda could not unzip the deployment package\. -HTTP Status Code: 502 - - **KMSAccessDeniedException** -Lambda was unable to decrypt the environment variables because KMS access was denied\. Check the Lambda function's KMS permissions\. -HTTP Status Code: 502 - - **KMSDisabledException** -Lambda was unable to decrypt the environment variables because the KMS key used is disabled\. Check the Lambda function's KMS key settings\. -HTTP Status Code: 502 - - **KMSInvalidStateException** -Lambda was unable to decrypt the environment variables because the KMS key used is in an invalid state for Decrypt\. Check the function's KMS key settings\. -HTTP Status Code: 502 - - **KMSNotFoundException** -Lambda was unable to decrypt the environment variables because the KMS key was not found\. Check the function's KMS key settings\. -HTTP Status Code: 502 - - **RequestTooLargeException** -The request payload exceeded the `Invoke` request body JSON input limit\. For more information, see [Limits](https://docs.aws.amazon.com/lambda/latest/dg/limits.html)\. -HTTP Status Code: 413 - - **ResourceConflictException** -The resource already exists, or another operation is in progress\. -HTTP Status Code: 409 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ResourceNotReadyException** -The function is inactive and its VPC connection is no longer available\. Wait for the VPC connection to reestablish and try again\. -HTTP Status Code: 502 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **SubnetIPAddressLimitReachedException** -AWS Lambda was not able to set up VPC access for the Lambda function because one or more configured subnets has no available IP addresses\. -HTTP Status Code: 502 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - - **UnsupportedMediaTypeException** -The content type of the `Invoke` request body is not JSON\. -HTTP Status Code: 415 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/Invoke) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/Invoke) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/Invoke) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/Invoke) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/Invoke) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/Invoke) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/Invoke) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/Invoke) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/Invoke) \ No newline at end of file diff --git a/doc_source/API_InvokeAsync.md b/doc_source/API_InvokeAsync.md deleted file mode 100644 index 112f8448..00000000 --- a/doc_source/API_InvokeAsync.md +++ /dev/null @@ -1,86 +0,0 @@ -# InvokeAsync - - *This action has been deprecated\.* - -**Important** -For asynchronous function invocation, use [Invoke](API_Invoke.md)\. - -Invokes a function asynchronously\. - -## Request Syntax - -``` -POST /2014-11-13/functions/FunctionName/invoke-async/ HTTP/1.1 - -InvokeArgs -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [FunctionName](#API_InvokeAsync_RequestSyntax) ** -The name of the Lambda function\. - -**Name formats** -+ **Function name** \- `my-function`\. -+ **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:my-function`\. -+ **Partial ARN** \- `123456789012:function:my-function`\. -The length constraint applies only to the full ARN\. If you specify only the function name, it is limited to 64 characters in length\. -Length Constraints: Minimum length of 1\. Maximum length of 170\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_\.]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - -## Request Body - -The request accepts the following binary data\. - - ** [InvokeArgs](#API_InvokeAsync_RequestSyntax) ** -The JSON that you want to provide to your Lambda function as input\. - -## Response Syntax - -``` -HTTP/1.1 Status -``` - -## Response Elements - -If the action is successful, the service sends back the following HTTP response\. - - ** [Status](#API_InvokeAsync_ResponseSyntax) ** -The status code\. - -## Errors - - **InvalidRequestContentException** -The request body could not be parsed as JSON\. -HTTP Status Code: 400 - - **InvalidRuntimeException** -The runtime or runtime version specified is not supported\. -HTTP Status Code: 502 - - **ResourceConflictException** -The resource already exists, or another operation is in progress\. -HTTP Status Code: 409 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/InvokeAsync) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/InvokeAsync) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/InvokeAsync) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/InvokeAsync) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/InvokeAsync) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/InvokeAsync) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/InvokeAsync) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/InvokeAsync) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/InvokeAsync) \ No newline at end of file diff --git a/doc_source/API_Layer.md b/doc_source/API_Layer.md deleted file mode 100644 index df0d9d16..00000000 --- a/doc_source/API_Layer.md +++ /dev/null @@ -1,25 +0,0 @@ -# Layer - -An [AWS Lambda layer](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)\. - -## Contents - - **Arn** -The Amazon Resource Name \(ARN\) of the function layer\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `arn:[a-zA-Z0-9-]+:lambda:[a-zA-Z0-9-]+:\d{12}:layer:[a-zA-Z0-9-_]+:[0-9]+` -Required: No - - **CodeSize** -The size of the layer archive in bytes\. -Type: Long -Required: No - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/Layer) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/Layer) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/Layer) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/Layer) \ No newline at end of file diff --git a/doc_source/API_LayerVersionContentInput.md b/doc_source/API_LayerVersionContentInput.md deleted file mode 100644 index df236db4..00000000 --- a/doc_source/API_LayerVersionContentInput.md +++ /dev/null @@ -1,37 +0,0 @@ -# LayerVersionContentInput - -A ZIP archive that contains the contents of an [AWS Lambda layer](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)\. You can specify either an Amazon S3 location, or upload a layer archive directly\. - -## Contents - - **S3Bucket** -The Amazon S3 bucket of the layer archive\. -Type: String -Length Constraints: Minimum length of 3\. Maximum length of 63\. -Pattern: `^[0-9A-Za-z\.\-_]*(? -The Amazon S3 key of the layer archive\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 1024\. -Required: No - - **S3ObjectVersion** -For versioned objects, the version of the layer archive object to use\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 1024\. -Required: No - - **ZipFile** -The base64\-encoded contents of the layer archive\. AWS SDK and AWS CLI clients handle the encoding for you\. -Type: Base64\-encoded binary data object -Required: No - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/LayerVersionContentInput) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/LayerVersionContentInput) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/LayerVersionContentInput) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/LayerVersionContentInput) \ No newline at end of file diff --git a/doc_source/API_LayerVersionContentOutput.md b/doc_source/API_LayerVersionContentOutput.md deleted file mode 100644 index 09f64516..00000000 --- a/doc_source/API_LayerVersionContentOutput.md +++ /dev/null @@ -1,28 +0,0 @@ -# LayerVersionContentOutput - -Details about a version of an [AWS Lambda layer](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)\. - -## Contents - - **CodeSha256** -The SHA\-256 hash of the layer archive\. -Type: String -Required: No - - **CodeSize** -The size of the layer archive in bytes\. -Type: Long -Required: No - - **Location** -A link to the layer archive in Amazon S3 that is valid for 10 minutes\. -Type: String -Required: No - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/LayerVersionContentOutput) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/LayerVersionContentOutput) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/LayerVersionContentOutput) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/LayerVersionContentOutput) \ No newline at end of file diff --git a/doc_source/API_LayerVersionsListItem.md b/doc_source/API_LayerVersionsListItem.md deleted file mode 100644 index 55c7c648..00000000 --- a/doc_source/API_LayerVersionsListItem.md +++ /dev/null @@ -1,49 +0,0 @@ -# LayerVersionsListItem - -Details about a version of an [AWS Lambda layer](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)\. - -## Contents - - **CompatibleRuntimes** -The layer's compatible runtimes\. -Type: Array of strings -Array Members: Maximum number of 5 items\. -Valid Values:` nodejs10.x | nodejs12.x | java8 | java11 | python2.7 | python3.6 | python3.7 | python3.8 | dotnetcore2.1 | go1.x | ruby2.5 | ruby2.7 | provided` -Required: No - - **CreatedDate** -The date that the version was created, in ISO 8601 format\. For example, `2018-11-27T15:10:45.123+0000`\. -Type: String -Required: No - - **Description** -The description of the version\. -Type: String -Length Constraints: Minimum length of 0\. Maximum length of 256\. -Required: No - - **LayerVersionArn** -The ARN of the layer version\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `arn:[a-zA-Z0-9-]+:lambda:[a-zA-Z0-9-]+:\d{12}:layer:[a-zA-Z0-9-_]+:[0-9]+` -Required: No - - **LicenseInfo** -The layer's open\-source license\. -Type: String -Length Constraints: Maximum length of 512\. -Required: No - - **Version** -The version number\. -Type: Long -Required: No - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/LayerVersionsListItem) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/LayerVersionsListItem) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/LayerVersionsListItem) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/LayerVersionsListItem) \ No newline at end of file diff --git a/doc_source/API_LayersListItem.md b/doc_source/API_LayersListItem.md deleted file mode 100644 index 96e5e748..00000000 --- a/doc_source/API_LayersListItem.md +++ /dev/null @@ -1,32 +0,0 @@ -# LayersListItem - -Details about an [AWS Lambda layer](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)\. - -## Contents - - **LatestMatchingVersion** -The newest version of the layer\. -Type: [LayerVersionsListItem](API_LayerVersionsListItem.md) object -Required: No - - **LayerArn** -The Amazon Resource Name \(ARN\) of the function layer\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `arn:[a-zA-Z0-9-]+:lambda:[a-zA-Z0-9-]+:\d{12}:layer:[a-zA-Z0-9-_]+` -Required: No - - **LayerName** -The name of the layer\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:[a-zA-Z0-9-]+:lambda:[a-zA-Z0-9-]+:\d{12}:layer:[a-zA-Z0-9-_]+)|[a-zA-Z0-9-_]+` -Required: No - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/LayersListItem) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/LayersListItem) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/LayersListItem) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/LayersListItem) \ No newline at end of file diff --git a/doc_source/API_ListAliases.md b/doc_source/API_ListAliases.md deleted file mode 100644 index bda44fc8..00000000 --- a/doc_source/API_ListAliases.md +++ /dev/null @@ -1,110 +0,0 @@ -# ListAliases - -Returns a list of [aliases](https://docs.aws.amazon.com/lambda/latest/dg/versioning-aliases.html) for a Lambda function\. - -## Request Syntax - -``` -GET /2015-03-31/functions/FunctionName/aliases?FunctionVersion=FunctionVersion&Marker=Marker&MaxItems=MaxItems HTTP/1.1 -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [FunctionName](#API_ListAliases_RequestSyntax) ** -The name of the Lambda function\. - -**Name formats** -+ **Function name** \- `MyFunction`\. -+ **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:MyFunction`\. -+ **Partial ARN** \- `123456789012:function:MyFunction`\. -The length constraint applies only to the full ARN\. If you specify only the function name, it is limited to 64 characters in length\. -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [FunctionVersion](#API_ListAliases_RequestSyntax) ** -Specify a function version to only list aliases that invoke that version\. -Length Constraints: Minimum length of 1\. Maximum length of 1024\. -Pattern: `(\$LATEST|[0-9]+)` - - ** [Marker](#API_ListAliases_RequestSyntax) ** -Specify the pagination token that's returned by a previous request to retrieve the next page of results\. - - ** [MaxItems](#API_ListAliases_RequestSyntax) ** -Limit the number of aliases returned\. -Valid Range: Minimum value of 1\. Maximum value of 10000\. - -## Request Body - -The request does not have a request body\. - -## Response Syntax - -``` -HTTP/1.1 200 -Content-type: application/json - -{ - "[Aliases](#SSS-ListAliases-response-Aliases)": [ - { - "[AliasArn](API_AliasConfiguration.md#SSS-Type-AliasConfiguration-AliasArn)": "string", - "[Description](API_AliasConfiguration.md#SSS-Type-AliasConfiguration-Description)": "string", - "[FunctionVersion](API_AliasConfiguration.md#SSS-Type-AliasConfiguration-FunctionVersion)": "string", - "[Name](API_AliasConfiguration.md#SSS-Type-AliasConfiguration-Name)": "string", - "[RevisionId](API_AliasConfiguration.md#SSS-Type-AliasConfiguration-RevisionId)": "string", - "[RoutingConfig](API_AliasConfiguration.md#SSS-Type-AliasConfiguration-RoutingConfig)": { - "[AdditionalVersionWeights](API_AliasRoutingConfiguration.md#SSS-Type-AliasRoutingConfiguration-AdditionalVersionWeights)": { - "string" : number - } - } - } - ], - "[NextMarker](#SSS-ListAliases-response-NextMarker)": "string" -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 200 response\. - -The following data is returned in JSON format by the service\. - - ** [Aliases](#API_ListAliases_ResponseSyntax) ** -A list of aliases\. -Type: Array of [AliasConfiguration](API_AliasConfiguration.md) objects - - ** [NextMarker](#API_ListAliases_ResponseSyntax) ** -The pagination token that's included if more results are available\. -Type: String - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/ListAliases) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/ListAliases) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/ListAliases) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/ListAliases) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/ListAliases) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/ListAliases) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/ListAliases) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/ListAliases) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/ListAliases) \ No newline at end of file diff --git a/doc_source/API_ListEventSourceMappings.md b/doc_source/API_ListEventSourceMappings.md deleted file mode 100644 index fe3a08ec..00000000 --- a/doc_source/API_ListEventSourceMappings.md +++ /dev/null @@ -1,124 +0,0 @@ -# ListEventSourceMappings - -Lists event source mappings\. Specify an `EventSourceArn` to only show event source mappings for a single event source\. - -## Request Syntax - -``` -GET /2015-03-31/event-source-mappings/?EventSourceArn=EventSourceArn&FunctionName=FunctionName&Marker=Marker&MaxItems=MaxItems HTTP/1.1 -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [EventSourceArn](#API_ListEventSourceMappings_RequestSyntax) ** -The Amazon Resource Name \(ARN\) of the event source\. -+ **Amazon Kinesis** \- The ARN of the data stream or a stream consumer\. -+ **Amazon DynamoDB Streams** \- The ARN of the stream\. -+ **Amazon Simple Queue Service** \- The ARN of the queue\. -Pattern: `arn:(aws[a-zA-Z0-9-]*):([a-zA-Z0-9\-])+:([a-z]{2}(-gov)?-[a-z]+-\d{1})?:(\d{12})?:(.*)` - - ** [FunctionName](#API_ListEventSourceMappings_RequestSyntax) ** -The name of the Lambda function\. - -**Name formats** -+ **Function name** \- `MyFunction`\. -+ **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:MyFunction`\. -+ **Version or Alias ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:MyFunction:PROD`\. -+ **Partial ARN** \- `123456789012:function:MyFunction`\. -The length constraint applies only to the full ARN\. If you specify only the function name, it's limited to 64 characters in length\. -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [Marker](#API_ListEventSourceMappings_RequestSyntax) ** -A pagination token returned by a previous call\. - - ** [MaxItems](#API_ListEventSourceMappings_RequestSyntax) ** -The maximum number of event source mappings to return\. -Valid Range: Minimum value of 1\. Maximum value of 10000\. - -## Request Body - -The request does not have a request body\. - -## Response Syntax - -``` -HTTP/1.1 200 -Content-type: application/json - -{ - "[EventSourceMappings](#SSS-ListEventSourceMappings-response-EventSourceMappings)": [ - { - "[BatchSize](API_EventSourceMappingConfiguration.md#SSS-Type-EventSourceMappingConfiguration-BatchSize)": number, - "[BisectBatchOnFunctionError](API_EventSourceMappingConfiguration.md#SSS-Type-EventSourceMappingConfiguration-BisectBatchOnFunctionError)": boolean, - "[DestinationConfig](API_EventSourceMappingConfiguration.md#SSS-Type-EventSourceMappingConfiguration-DestinationConfig)": { - "[OnFailure](API_DestinationConfig.md#SSS-Type-DestinationConfig-OnFailure)": { - "[Destination](API_OnFailure.md#SSS-Type-OnFailure-Destination)": "string" - }, - "[OnSuccess](API_DestinationConfig.md#SSS-Type-DestinationConfig-OnSuccess)": { - "[Destination](API_OnSuccess.md#SSS-Type-OnSuccess-Destination)": "string" - } - }, - "[EventSourceArn](API_EventSourceMappingConfiguration.md#SSS-Type-EventSourceMappingConfiguration-EventSourceArn)": "string", - "[FunctionArn](API_EventSourceMappingConfiguration.md#SSS-Type-EventSourceMappingConfiguration-FunctionArn)": "string", - "[LastModified](API_EventSourceMappingConfiguration.md#SSS-Type-EventSourceMappingConfiguration-LastModified)": number, - "[LastProcessingResult](API_EventSourceMappingConfiguration.md#SSS-Type-EventSourceMappingConfiguration-LastProcessingResult)": "string", - "[MaximumBatchingWindowInSeconds](API_EventSourceMappingConfiguration.md#SSS-Type-EventSourceMappingConfiguration-MaximumBatchingWindowInSeconds)": number, - "[MaximumRecordAgeInSeconds](API_EventSourceMappingConfiguration.md#SSS-Type-EventSourceMappingConfiguration-MaximumRecordAgeInSeconds)": number, - "[MaximumRetryAttempts](API_EventSourceMappingConfiguration.md#SSS-Type-EventSourceMappingConfiguration-MaximumRetryAttempts)": number, - "[ParallelizationFactor](API_EventSourceMappingConfiguration.md#SSS-Type-EventSourceMappingConfiguration-ParallelizationFactor)": number, - "[State](API_EventSourceMappingConfiguration.md#SSS-Type-EventSourceMappingConfiguration-State)": "string", - "[StateTransitionReason](API_EventSourceMappingConfiguration.md#SSS-Type-EventSourceMappingConfiguration-StateTransitionReason)": "string", - "[UUID](API_EventSourceMappingConfiguration.md#SSS-Type-EventSourceMappingConfiguration-UUID)": "string" - } - ], - "[NextMarker](#SSS-ListEventSourceMappings-response-NextMarker)": "string" -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 200 response\. - -The following data is returned in JSON format by the service\. - - ** [EventSourceMappings](#API_ListEventSourceMappings_ResponseSyntax) ** -A list of event source mappings\. -Type: Array of [EventSourceMappingConfiguration](API_EventSourceMappingConfiguration.md) objects - - ** [NextMarker](#API_ListEventSourceMappings_ResponseSyntax) ** -A pagination token that's returned when the response doesn't contain all event source mappings\. -Type: String - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/ListEventSourceMappings) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/ListEventSourceMappings) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/ListEventSourceMappings) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/ListEventSourceMappings) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/ListEventSourceMappings) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/ListEventSourceMappings) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/ListEventSourceMappings) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/ListEventSourceMappings) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/ListEventSourceMappings) \ No newline at end of file diff --git a/doc_source/API_ListFunctionEventInvokeConfigs.md b/doc_source/API_ListFunctionEventInvokeConfigs.md deleted file mode 100644 index 07beda58..00000000 --- a/doc_source/API_ListFunctionEventInvokeConfigs.md +++ /dev/null @@ -1,109 +0,0 @@ -# ListFunctionEventInvokeConfigs - -Retrieves a list of configurations for asynchronous invocation for a function\. - -To configure options for asynchronous invocation, use [PutFunctionEventInvokeConfig](API_PutFunctionEventInvokeConfig.md)\. - -## Request Syntax - -``` -GET /2019-09-25/functions/FunctionName/event-invoke-config/list?Marker=Marker&MaxItems=MaxItems HTTP/1.1 -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [FunctionName](#API_ListFunctionEventInvokeConfigs_RequestSyntax) ** -The name of the Lambda function\. - -**Name formats** -+ **Function name** \- `my-function`\. -+ **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:my-function`\. -+ **Partial ARN** \- `123456789012:function:my-function`\. -The length constraint applies only to the full ARN\. If you specify only the function name, it is limited to 64 characters in length\. -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [Marker](#API_ListFunctionEventInvokeConfigs_RequestSyntax) ** -Specify the pagination token that's returned by a previous request to retrieve the next page of results\. - - ** [MaxItems](#API_ListFunctionEventInvokeConfigs_RequestSyntax) ** -The maximum number of configurations to return\. -Valid Range: Minimum value of 1\. Maximum value of 50\. - -## Request Body - -The request does not have a request body\. - -## Response Syntax - -``` -HTTP/1.1 200 -Content-type: application/json - -{ - "[FunctionEventInvokeConfigs](#SSS-ListFunctionEventInvokeConfigs-response-FunctionEventInvokeConfigs)": [ - { - "[DestinationConfig](API_FunctionEventInvokeConfig.md#SSS-Type-FunctionEventInvokeConfig-DestinationConfig)": { - "[OnFailure](API_DestinationConfig.md#SSS-Type-DestinationConfig-OnFailure)": { - "[Destination](API_OnFailure.md#SSS-Type-OnFailure-Destination)": "string" - }, - "[OnSuccess](API_DestinationConfig.md#SSS-Type-DestinationConfig-OnSuccess)": { - "[Destination](API_OnSuccess.md#SSS-Type-OnSuccess-Destination)": "string" - } - }, - "[FunctionArn](API_FunctionEventInvokeConfig.md#SSS-Type-FunctionEventInvokeConfig-FunctionArn)": "string", - "[LastModified](API_FunctionEventInvokeConfig.md#SSS-Type-FunctionEventInvokeConfig-LastModified)": number, - "[MaximumEventAgeInSeconds](API_FunctionEventInvokeConfig.md#SSS-Type-FunctionEventInvokeConfig-MaximumEventAgeInSeconds)": number, - "[MaximumRetryAttempts](API_FunctionEventInvokeConfig.md#SSS-Type-FunctionEventInvokeConfig-MaximumRetryAttempts)": number - } - ], - "[NextMarker](#SSS-ListFunctionEventInvokeConfigs-response-NextMarker)": "string" -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 200 response\. - -The following data is returned in JSON format by the service\. - - ** [FunctionEventInvokeConfigs](#API_ListFunctionEventInvokeConfigs_ResponseSyntax) ** -A list of configurations\. -Type: Array of [FunctionEventInvokeConfig](API_FunctionEventInvokeConfig.md) objects - - ** [NextMarker](#API_ListFunctionEventInvokeConfigs_ResponseSyntax) ** -The pagination token that's included if more results are available\. -Type: String - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/ListFunctionEventInvokeConfigs) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/ListFunctionEventInvokeConfigs) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/ListFunctionEventInvokeConfigs) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/ListFunctionEventInvokeConfigs) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/ListFunctionEventInvokeConfigs) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/ListFunctionEventInvokeConfigs) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/ListFunctionEventInvokeConfigs) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/ListFunctionEventInvokeConfigs) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/ListFunctionEventInvokeConfigs) \ No newline at end of file diff --git a/doc_source/API_ListFunctions.md b/doc_source/API_ListFunctions.md deleted file mode 100644 index 7c048ede..00000000 --- a/doc_source/API_ListFunctions.md +++ /dev/null @@ -1,137 +0,0 @@ -# ListFunctions - -Returns a list of Lambda functions, with the version\-specific configuration of each\. Lambda returns up to 50 functions per call\. - -Set `FunctionVersion` to `ALL` to include all published versions of each function in addition to the unpublished version\. To get more information about a function or version, use [GetFunction](API_GetFunction.md)\. - -## Request Syntax - -``` -GET /2015-03-31/functions/?FunctionVersion=FunctionVersion&Marker=Marker&MasterRegion=MasterRegion&MaxItems=MaxItems HTTP/1.1 -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [FunctionVersion](#API_ListFunctions_RequestSyntax) ** -Set to `ALL` to include entries for all published versions of each function\. -Valid Values:` ALL` - - ** [Marker](#API_ListFunctions_RequestSyntax) ** -Specify the pagination token that's returned by a previous request to retrieve the next page of results\. - - ** [MasterRegion](#API_ListFunctions_RequestSyntax) ** -For Lambda@Edge functions, the AWS Region of the master function\. For example, `us-east-1` filters the list of functions to only include Lambda@Edge functions replicated from a master function in US East \(N\. Virginia\)\. If specified, you must set `FunctionVersion` to `ALL`\. -Pattern: `ALL|[a-z]{2}(-gov)?-[a-z]+-\d{1}` - - ** [MaxItems](#API_ListFunctions_RequestSyntax) ** -The maximum number of functions to return\. -Valid Range: Minimum value of 1\. Maximum value of 10000\. - -## Request Body - -The request does not have a request body\. - -## Response Syntax - -``` -HTTP/1.1 200 -Content-type: application/json - -{ - "[Functions](#SSS-ListFunctions-response-Functions)": [ - { - "[CodeSha256](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-CodeSha256)": "string", - "[CodeSize](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-CodeSize)": number, - "[DeadLetterConfig](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-DeadLetterConfig)": { - "[TargetArn](API_DeadLetterConfig.md#SSS-Type-DeadLetterConfig-TargetArn)": "string" - }, - "[Description](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-Description)": "string", - "[Environment](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-Environment)": { - "[Error](API_EnvironmentResponse.md#SSS-Type-EnvironmentResponse-Error)": { - "[ErrorCode](API_EnvironmentError.md#SSS-Type-EnvironmentError-ErrorCode)": "string", - "[Message](API_EnvironmentError.md#SSS-Type-EnvironmentError-Message)": "string" - }, - "[Variables](API_EnvironmentResponse.md#SSS-Type-EnvironmentResponse-Variables)": { - "string" : "string" - } - }, - "[FunctionArn](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-FunctionArn)": "string", - "[FunctionName](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-FunctionName)": "string", - "[Handler](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-Handler)": "string", - "[KMSKeyArn](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-KMSKeyArn)": "string", - "[LastModified](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-LastModified)": "string", - "[LastUpdateStatus](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-LastUpdateStatus)": "string", - "[LastUpdateStatusReason](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-LastUpdateStatusReason)": "string", - "[LastUpdateStatusReasonCode](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-LastUpdateStatusReasonCode)": "string", - "[Layers](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-Layers)": [ - { - "[Arn](API_Layer.md#SSS-Type-Layer-Arn)": "string", - "[CodeSize](API_Layer.md#SSS-Type-Layer-CodeSize)": number - } - ], - "[MasterArn](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-MasterArn)": "string", - "[MemorySize](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-MemorySize)": number, - "[RevisionId](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-RevisionId)": "string", - "[Role](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-Role)": "string", - "[Runtime](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-Runtime)": "string", - "[State](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-State)": "string", - "[StateReason](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-StateReason)": "string", - "[StateReasonCode](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-StateReasonCode)": "string", - "[Timeout](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-Timeout)": number, - "[TracingConfig](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-TracingConfig)": { - "[Mode](API_TracingConfigResponse.md#SSS-Type-TracingConfigResponse-Mode)": "string" - }, - "[Version](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-Version)": "string", - "[VpcConfig](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-VpcConfig)": { - "[SecurityGroupIds](API_VpcConfigResponse.md#SSS-Type-VpcConfigResponse-SecurityGroupIds)": [ "string" ], - "[SubnetIds](API_VpcConfigResponse.md#SSS-Type-VpcConfigResponse-SubnetIds)": [ "string" ], - "[VpcId](API_VpcConfigResponse.md#SSS-Type-VpcConfigResponse-VpcId)": "string" - } - } - ], - "[NextMarker](#SSS-ListFunctions-response-NextMarker)": "string" -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 200 response\. - -The following data is returned in JSON format by the service\. - - ** [Functions](#API_ListFunctions_ResponseSyntax) ** -A list of Lambda functions\. -Type: Array of [FunctionConfiguration](API_FunctionConfiguration.md) objects - - ** [NextMarker](#API_ListFunctions_ResponseSyntax) ** -The pagination token that's included if more results are available\. -Type: String - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/ListFunctions) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/ListFunctions) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/ListFunctions) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/ListFunctions) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/ListFunctions) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/ListFunctions) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/ListFunctions) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/ListFunctions) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/ListFunctions) \ No newline at end of file diff --git a/doc_source/API_ListLayerVersions.md b/doc_source/API_ListLayerVersions.md deleted file mode 100644 index daa591ac..00000000 --- a/doc_source/API_ListLayerVersions.md +++ /dev/null @@ -1,99 +0,0 @@ -# ListLayerVersions - -Lists the versions of an [AWS Lambda layer](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)\. Versions that have been deleted aren't listed\. Specify a [runtime identifier](https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html) to list only versions that indicate that they're compatible with that runtime\. - -## Request Syntax - -``` -GET /2018-10-31/layers/LayerName/versions?CompatibleRuntime=CompatibleRuntime&Marker=Marker&MaxItems=MaxItems HTTP/1.1 -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [CompatibleRuntime](#API_ListLayerVersions_RequestSyntax) ** -A runtime identifier\. For example, `go1.x`\. -Valid Values:` nodejs10.x | nodejs12.x | java8 | java11 | python2.7 | python3.6 | python3.7 | python3.8 | dotnetcore2.1 | go1.x | ruby2.5 | ruby2.7 | provided` - - ** [LayerName](#API_ListLayerVersions_RequestSyntax) ** -The name or Amazon Resource Name \(ARN\) of the layer\. -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:[a-zA-Z0-9-]+:lambda:[a-zA-Z0-9-]+:\d{12}:layer:[a-zA-Z0-9-_]+)|[a-zA-Z0-9-_]+` - - ** [Marker](#API_ListLayerVersions_RequestSyntax) ** -A pagination token returned by a previous call\. - - ** [MaxItems](#API_ListLayerVersions_RequestSyntax) ** -The maximum number of versions to return\. -Valid Range: Minimum value of 1\. Maximum value of 50\. - -## Request Body - -The request does not have a request body\. - -## Response Syntax - -``` -HTTP/1.1 200 -Content-type: application/json - -{ - "[LayerVersions](#SSS-ListLayerVersions-response-LayerVersions)": [ - { - "[CompatibleRuntimes](API_LayerVersionsListItem.md#SSS-Type-LayerVersionsListItem-CompatibleRuntimes)": [ "string" ], - "[CreatedDate](API_LayerVersionsListItem.md#SSS-Type-LayerVersionsListItem-CreatedDate)": "string", - "[Description](API_LayerVersionsListItem.md#SSS-Type-LayerVersionsListItem-Description)": "string", - "[LayerVersionArn](API_LayerVersionsListItem.md#SSS-Type-LayerVersionsListItem-LayerVersionArn)": "string", - "[LicenseInfo](API_LayerVersionsListItem.md#SSS-Type-LayerVersionsListItem-LicenseInfo)": "string", - "[Version](API_LayerVersionsListItem.md#SSS-Type-LayerVersionsListItem-Version)": number - } - ], - "[NextMarker](#SSS-ListLayerVersions-response-NextMarker)": "string" -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 200 response\. - -The following data is returned in JSON format by the service\. - - ** [LayerVersions](#API_ListLayerVersions_ResponseSyntax) ** -A list of versions\. -Type: Array of [LayerVersionsListItem](API_LayerVersionsListItem.md) objects - - ** [NextMarker](#API_ListLayerVersions_ResponseSyntax) ** -A pagination token returned when the response doesn't contain all versions\. -Type: String - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/ListLayerVersions) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/ListLayerVersions) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/ListLayerVersions) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/ListLayerVersions) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/ListLayerVersions) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/ListLayerVersions) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/ListLayerVersions) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/ListLayerVersions) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/ListLayerVersions) \ No newline at end of file diff --git a/doc_source/API_ListLayers.md b/doc_source/API_ListLayers.md deleted file mode 100644 index 9c722148..00000000 --- a/doc_source/API_ListLayers.md +++ /dev/null @@ -1,94 +0,0 @@ -# ListLayers - -Lists [AWS Lambda layers](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) and shows information about the latest version of each\. Specify a [runtime identifier](https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html) to list only layers that indicate that they're compatible with that runtime\. - -## Request Syntax - -``` -GET /2018-10-31/layers?CompatibleRuntime=CompatibleRuntime&Marker=Marker&MaxItems=MaxItems HTTP/1.1 -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [CompatibleRuntime](#API_ListLayers_RequestSyntax) ** -A runtime identifier\. For example, `go1.x`\. -Valid Values:` nodejs10.x | nodejs12.x | java8 | java11 | python2.7 | python3.6 | python3.7 | python3.8 | dotnetcore2.1 | go1.x | ruby2.5 | ruby2.7 | provided` - - ** [Marker](#API_ListLayers_RequestSyntax) ** -A pagination token returned by a previous call\. - - ** [MaxItems](#API_ListLayers_RequestSyntax) ** -The maximum number of layers to return\. -Valid Range: Minimum value of 1\. Maximum value of 50\. - -## Request Body - -The request does not have a request body\. - -## Response Syntax - -``` -HTTP/1.1 200 -Content-type: application/json - -{ - "[Layers](#SSS-ListLayers-response-Layers)": [ - { - "[LatestMatchingVersion](API_LayersListItem.md#SSS-Type-LayersListItem-LatestMatchingVersion)": { - "[CompatibleRuntimes](API_LayerVersionsListItem.md#SSS-Type-LayerVersionsListItem-CompatibleRuntimes)": [ "string" ], - "[CreatedDate](API_LayerVersionsListItem.md#SSS-Type-LayerVersionsListItem-CreatedDate)": "string", - "[Description](API_LayerVersionsListItem.md#SSS-Type-LayerVersionsListItem-Description)": "string", - "[LayerVersionArn](API_LayerVersionsListItem.md#SSS-Type-LayerVersionsListItem-LayerVersionArn)": "string", - "[LicenseInfo](API_LayerVersionsListItem.md#SSS-Type-LayerVersionsListItem-LicenseInfo)": "string", - "[Version](API_LayerVersionsListItem.md#SSS-Type-LayerVersionsListItem-Version)": number - }, - "[LayerArn](API_LayersListItem.md#SSS-Type-LayersListItem-LayerArn)": "string", - "[LayerName](API_LayersListItem.md#SSS-Type-LayersListItem-LayerName)": "string" - } - ], - "[NextMarker](#SSS-ListLayers-response-NextMarker)": "string" -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 200 response\. - -The following data is returned in JSON format by the service\. - - ** [Layers](#API_ListLayers_ResponseSyntax) ** -A list of function layers\. -Type: Array of [LayersListItem](API_LayersListItem.md) objects - - ** [NextMarker](#API_ListLayers_ResponseSyntax) ** -A pagination token returned when the response doesn't contain all layers\. -Type: String - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/ListLayers) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/ListLayers) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/ListLayers) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/ListLayers) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/ListLayers) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/ListLayers) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/ListLayers) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/ListLayers) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/ListLayers) \ No newline at end of file diff --git a/doc_source/API_ListProvisionedConcurrencyConfigs.md b/doc_source/API_ListProvisionedConcurrencyConfigs.md deleted file mode 100644 index b78cb1eb..00000000 --- a/doc_source/API_ListProvisionedConcurrencyConfigs.md +++ /dev/null @@ -1,102 +0,0 @@ -# ListProvisionedConcurrencyConfigs - -Retrieves a list of provisioned concurrency configurations for a function\. - -## Request Syntax - -``` -GET /2019-09-30/functions/FunctionName/provisioned-concurrency?List=ALL&Marker=Marker&MaxItems=MaxItems HTTP/1.1 -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [FunctionName](#API_ListProvisionedConcurrencyConfigs_RequestSyntax) ** -The name of the Lambda function\. - -**Name formats** -+ **Function name** \- `my-function`\. -+ **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:my-function`\. -+ **Partial ARN** \- `123456789012:function:my-function`\. -The length constraint applies only to the full ARN\. If you specify only the function name, it is limited to 64 characters in length\. -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [Marker](#API_ListProvisionedConcurrencyConfigs_RequestSyntax) ** -Specify the pagination token that's returned by a previous request to retrieve the next page of results\. - - ** [MaxItems](#API_ListProvisionedConcurrencyConfigs_RequestSyntax) ** -Specify a number to limit the number of configurations returned\. -Valid Range: Minimum value of 1\. Maximum value of 50\. - -## Request Body - -The request does not have a request body\. - -## Response Syntax - -``` -HTTP/1.1 200 -Content-type: application/json - -{ - "[NextMarker](#SSS-ListProvisionedConcurrencyConfigs-response-NextMarker)": "string", - "[ProvisionedConcurrencyConfigs](#SSS-ListProvisionedConcurrencyConfigs-response-ProvisionedConcurrencyConfigs)": [ - { - "[AllocatedProvisionedConcurrentExecutions](API_ProvisionedConcurrencyConfigListItem.md#SSS-Type-ProvisionedConcurrencyConfigListItem-AllocatedProvisionedConcurrentExecutions)": number, - "[AvailableProvisionedConcurrentExecutions](API_ProvisionedConcurrencyConfigListItem.md#SSS-Type-ProvisionedConcurrencyConfigListItem-AvailableProvisionedConcurrentExecutions)": number, - "[FunctionArn](API_ProvisionedConcurrencyConfigListItem.md#SSS-Type-ProvisionedConcurrencyConfigListItem-FunctionArn)": "string", - "[LastModified](API_ProvisionedConcurrencyConfigListItem.md#SSS-Type-ProvisionedConcurrencyConfigListItem-LastModified)": "string", - "[RequestedProvisionedConcurrentExecutions](API_ProvisionedConcurrencyConfigListItem.md#SSS-Type-ProvisionedConcurrencyConfigListItem-RequestedProvisionedConcurrentExecutions)": number, - "[Status](API_ProvisionedConcurrencyConfigListItem.md#SSS-Type-ProvisionedConcurrencyConfigListItem-Status)": "string", - "[StatusReason](API_ProvisionedConcurrencyConfigListItem.md#SSS-Type-ProvisionedConcurrencyConfigListItem-StatusReason)": "string" - } - ] -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 200 response\. - -The following data is returned in JSON format by the service\. - - ** [NextMarker](#API_ListProvisionedConcurrencyConfigs_ResponseSyntax) ** -The pagination token that's included if more results are available\. -Type: String - - ** [ProvisionedConcurrencyConfigs](#API_ListProvisionedConcurrencyConfigs_ResponseSyntax) ** -A list of provisioned concurrency configurations\. -Type: Array of [ProvisionedConcurrencyConfigListItem](API_ProvisionedConcurrencyConfigListItem.md) objects - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/ListProvisionedConcurrencyConfigs) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/ListProvisionedConcurrencyConfigs) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/ListProvisionedConcurrencyConfigs) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/ListProvisionedConcurrencyConfigs) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/ListProvisionedConcurrencyConfigs) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/ListProvisionedConcurrencyConfigs) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/ListProvisionedConcurrencyConfigs) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/ListProvisionedConcurrencyConfigs) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/ListProvisionedConcurrencyConfigs) \ No newline at end of file diff --git a/doc_source/API_ListTags.md b/doc_source/API_ListTags.md deleted file mode 100644 index ac77cc79..00000000 --- a/doc_source/API_ListTags.md +++ /dev/null @@ -1,75 +0,0 @@ -# ListTags - -Returns a function's [tags](https://docs.aws.amazon.com/lambda/latest/dg/tagging.html)\. You can also view tags with [GetFunction](API_GetFunction.md)\. - -## Request Syntax - -``` -GET /2017-03-31/tags/ARN HTTP/1.1 -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [ARN](#API_ListTags_RequestSyntax) ** -The function's Amazon Resource Name \(ARN\)\. -Pattern: `arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}(-gov)?-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?` - -## Request Body - -The request does not have a request body\. - -## Response Syntax - -``` -HTTP/1.1 200 -Content-type: application/json - -{ - "[Tags](#SSS-ListTags-response-Tags)": { - "string" : "string" - } -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 200 response\. - -The following data is returned in JSON format by the service\. - - ** [Tags](#API_ListTags_ResponseSyntax) ** -The function's tags\. -Type: String to string map - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/ListTags) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/ListTags) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/ListTags) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/ListTags) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/ListTags) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/ListTags) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/ListTags) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/ListTags) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/ListTags) \ No newline at end of file diff --git a/doc_source/API_ListVersionsByFunction.md b/doc_source/API_ListVersionsByFunction.md deleted file mode 100644 index aee1cdcd..00000000 --- a/doc_source/API_ListVersionsByFunction.md +++ /dev/null @@ -1,142 +0,0 @@ -# ListVersionsByFunction - -Returns a list of [versions](https://docs.aws.amazon.com/lambda/latest/dg/versioning-aliases.html), with the version\-specific configuration of each\. Lambda returns up to 50 versions per call\. - -## Request Syntax - -``` -GET /2015-03-31/functions/FunctionName/versions?Marker=Marker&MaxItems=MaxItems HTTP/1.1 -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [FunctionName](#API_ListVersionsByFunction_RequestSyntax) ** -The name of the Lambda function\. - -**Name formats** -+ **Function name** \- `MyFunction`\. -+ **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:MyFunction`\. -+ **Partial ARN** \- `123456789012:function:MyFunction`\. -The length constraint applies only to the full ARN\. If you specify only the function name, it is limited to 64 characters in length\. -Length Constraints: Minimum length of 1\. Maximum length of 170\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_\.]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [Marker](#API_ListVersionsByFunction_RequestSyntax) ** -Specify the pagination token that's returned by a previous request to retrieve the next page of results\. - - ** [MaxItems](#API_ListVersionsByFunction_RequestSyntax) ** -The maximum number of versions to return\. -Valid Range: Minimum value of 1\. Maximum value of 10000\. - -## Request Body - -The request does not have a request body\. - -## Response Syntax - -``` -HTTP/1.1 200 -Content-type: application/json - -{ - "[NextMarker](#SSS-ListVersionsByFunction-response-NextMarker)": "string", - "[Versions](#SSS-ListVersionsByFunction-response-Versions)": [ - { - "[CodeSha256](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-CodeSha256)": "string", - "[CodeSize](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-CodeSize)": number, - "[DeadLetterConfig](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-DeadLetterConfig)": { - "[TargetArn](API_DeadLetterConfig.md#SSS-Type-DeadLetterConfig-TargetArn)": "string" - }, - "[Description](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-Description)": "string", - "[Environment](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-Environment)": { - "[Error](API_EnvironmentResponse.md#SSS-Type-EnvironmentResponse-Error)": { - "[ErrorCode](API_EnvironmentError.md#SSS-Type-EnvironmentError-ErrorCode)": "string", - "[Message](API_EnvironmentError.md#SSS-Type-EnvironmentError-Message)": "string" - }, - "[Variables](API_EnvironmentResponse.md#SSS-Type-EnvironmentResponse-Variables)": { - "string" : "string" - } - }, - "[FunctionArn](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-FunctionArn)": "string", - "[FunctionName](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-FunctionName)": "string", - "[Handler](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-Handler)": "string", - "[KMSKeyArn](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-KMSKeyArn)": "string", - "[LastModified](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-LastModified)": "string", - "[LastUpdateStatus](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-LastUpdateStatus)": "string", - "[LastUpdateStatusReason](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-LastUpdateStatusReason)": "string", - "[LastUpdateStatusReasonCode](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-LastUpdateStatusReasonCode)": "string", - "[Layers](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-Layers)": [ - { - "[Arn](API_Layer.md#SSS-Type-Layer-Arn)": "string", - "[CodeSize](API_Layer.md#SSS-Type-Layer-CodeSize)": number - } - ], - "[MasterArn](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-MasterArn)": "string", - "[MemorySize](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-MemorySize)": number, - "[RevisionId](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-RevisionId)": "string", - "[Role](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-Role)": "string", - "[Runtime](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-Runtime)": "string", - "[State](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-State)": "string", - "[StateReason](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-StateReason)": "string", - "[StateReasonCode](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-StateReasonCode)": "string", - "[Timeout](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-Timeout)": number, - "[TracingConfig](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-TracingConfig)": { - "[Mode](API_TracingConfigResponse.md#SSS-Type-TracingConfigResponse-Mode)": "string" - }, - "[Version](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-Version)": "string", - "[VpcConfig](API_FunctionConfiguration.md#SSS-Type-FunctionConfiguration-VpcConfig)": { - "[SecurityGroupIds](API_VpcConfigResponse.md#SSS-Type-VpcConfigResponse-SecurityGroupIds)": [ "string" ], - "[SubnetIds](API_VpcConfigResponse.md#SSS-Type-VpcConfigResponse-SubnetIds)": [ "string" ], - "[VpcId](API_VpcConfigResponse.md#SSS-Type-VpcConfigResponse-VpcId)": "string" - } - } - ] -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 200 response\. - -The following data is returned in JSON format by the service\. - - ** [NextMarker](#API_ListVersionsByFunction_ResponseSyntax) ** -The pagination token that's included if more results are available\. -Type: String - - ** [Versions](#API_ListVersionsByFunction_ResponseSyntax) ** -A list of Lambda function versions\. -Type: Array of [FunctionConfiguration](API_FunctionConfiguration.md) objects - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/ListVersionsByFunction) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/ListVersionsByFunction) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/ListVersionsByFunction) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/ListVersionsByFunction) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/ListVersionsByFunction) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/ListVersionsByFunction) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/ListVersionsByFunction) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/ListVersionsByFunction) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/ListVersionsByFunction) \ No newline at end of file diff --git a/doc_source/API_OnFailure.md b/doc_source/API_OnFailure.md deleted file mode 100644 index 144e32dc..00000000 --- a/doc_source/API_OnFailure.md +++ /dev/null @@ -1,20 +0,0 @@ -# OnFailure - -A destination for events that failed processing\. - -## Contents - - **Destination** -The Amazon Resource Name \(ARN\) of the destination resource\. -Type: String -Length Constraints: Minimum length of 0\. Maximum length of 350\. -Pattern: `^$|arn:(aws[a-zA-Z0-9-]*):([a-zA-Z0-9\-])+:([a-z]{2}(-gov)?-[a-z]+-\d{1})?:(\d{12})?:(.*)` -Required: No - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/OnFailure) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/OnFailure) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/OnFailure) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/OnFailure) \ No newline at end of file diff --git a/doc_source/API_OnSuccess.md b/doc_source/API_OnSuccess.md deleted file mode 100644 index 97935571..00000000 --- a/doc_source/API_OnSuccess.md +++ /dev/null @@ -1,20 +0,0 @@ -# OnSuccess - -A destination for events that were processed successfully\. - -## Contents - - **Destination** -The Amazon Resource Name \(ARN\) of the destination resource\. -Type: String -Length Constraints: Minimum length of 0\. Maximum length of 350\. -Pattern: `^$|arn:(aws[a-zA-Z0-9-]*):([a-zA-Z0-9\-])+:([a-z]{2}(-gov)?-[a-z]+-\d{1})?:(\d{12})?:(.*)` -Required: No - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/OnSuccess) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/OnSuccess) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/OnSuccess) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/OnSuccess) \ No newline at end of file diff --git a/doc_source/API_Operations.md b/doc_source/API_Operations.md deleted file mode 100644 index 4dedc902..00000000 --- a/doc_source/API_Operations.md +++ /dev/null @@ -1,52 +0,0 @@ -# Actions - -The following actions are supported: -+ [AddLayerVersionPermission](API_AddLayerVersionPermission.md) -+ [AddPermission](API_AddPermission.md) -+ [CreateAlias](API_CreateAlias.md) -+ [CreateEventSourceMapping](API_CreateEventSourceMapping.md) -+ [CreateFunction](API_CreateFunction.md) -+ [DeleteAlias](API_DeleteAlias.md) -+ [DeleteEventSourceMapping](API_DeleteEventSourceMapping.md) -+ [DeleteFunction](API_DeleteFunction.md) -+ [DeleteFunctionConcurrency](API_DeleteFunctionConcurrency.md) -+ [DeleteFunctionEventInvokeConfig](API_DeleteFunctionEventInvokeConfig.md) -+ [DeleteLayerVersion](API_DeleteLayerVersion.md) -+ [DeleteProvisionedConcurrencyConfig](API_DeleteProvisionedConcurrencyConfig.md) -+ [GetAccountSettings](API_GetAccountSettings.md) -+ [GetAlias](API_GetAlias.md) -+ [GetEventSourceMapping](API_GetEventSourceMapping.md) -+ [GetFunction](API_GetFunction.md) -+ [GetFunctionConcurrency](API_GetFunctionConcurrency.md) -+ [GetFunctionConfiguration](API_GetFunctionConfiguration.md) -+ [GetFunctionEventInvokeConfig](API_GetFunctionEventInvokeConfig.md) -+ [GetLayerVersion](API_GetLayerVersion.md) -+ [GetLayerVersionByArn](API_GetLayerVersionByArn.md) -+ [GetLayerVersionPolicy](API_GetLayerVersionPolicy.md) -+ [GetPolicy](API_GetPolicy.md) -+ [GetProvisionedConcurrencyConfig](API_GetProvisionedConcurrencyConfig.md) -+ [Invoke](API_Invoke.md) -+ [InvokeAsync](API_InvokeAsync.md) -+ [ListAliases](API_ListAliases.md) -+ [ListEventSourceMappings](API_ListEventSourceMappings.md) -+ [ListFunctionEventInvokeConfigs](API_ListFunctionEventInvokeConfigs.md) -+ [ListFunctions](API_ListFunctions.md) -+ [ListLayers](API_ListLayers.md) -+ [ListLayerVersions](API_ListLayerVersions.md) -+ [ListProvisionedConcurrencyConfigs](API_ListProvisionedConcurrencyConfigs.md) -+ [ListTags](API_ListTags.md) -+ [ListVersionsByFunction](API_ListVersionsByFunction.md) -+ [PublishLayerVersion](API_PublishLayerVersion.md) -+ [PublishVersion](API_PublishVersion.md) -+ [PutFunctionConcurrency](API_PutFunctionConcurrency.md) -+ [PutFunctionEventInvokeConfig](API_PutFunctionEventInvokeConfig.md) -+ [PutProvisionedConcurrencyConfig](API_PutProvisionedConcurrencyConfig.md) -+ [RemoveLayerVersionPermission](API_RemoveLayerVersionPermission.md) -+ [RemovePermission](API_RemovePermission.md) -+ [TagResource](API_TagResource.md) -+ [UntagResource](API_UntagResource.md) -+ [UpdateAlias](API_UpdateAlias.md) -+ [UpdateEventSourceMapping](API_UpdateEventSourceMapping.md) -+ [UpdateFunctionCode](API_UpdateFunctionCode.md) -+ [UpdateFunctionConfiguration](API_UpdateFunctionConfiguration.md) -+ [UpdateFunctionEventInvokeConfig](API_UpdateFunctionEventInvokeConfig.md) \ No newline at end of file diff --git a/doc_source/API_ProvisionedConcurrencyConfigListItem.md b/doc_source/API_ProvisionedConcurrencyConfigListItem.md deleted file mode 100644 index 7325b710..00000000 --- a/doc_source/API_ProvisionedConcurrencyConfigListItem.md +++ /dev/null @@ -1,53 +0,0 @@ -# ProvisionedConcurrencyConfigListItem - -Details about the provisioned concurrency configuration for a function alias or version\. - -## Contents - - **AllocatedProvisionedConcurrentExecutions** -The amount of provisioned concurrency allocated\. -Type: Integer -Valid Range: Minimum value of 0\. -Required: No - - **AvailableProvisionedConcurrentExecutions** -The amount of provisioned concurrency available\. -Type: Integer -Valid Range: Minimum value of 0\. -Required: No - - **FunctionArn** -The Amazon Resource Name \(ARN\) of the alias or version\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}(-gov)?-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?` -Required: No - - **LastModified** -The date and time that a user last updated the configuration, in [ISO 8601 format](https://www.iso.org/iso-8601-date-and-time-format.html)\. -Type: String -Required: No - - **RequestedProvisionedConcurrentExecutions** -The amount of provisioned concurrency requested\. -Type: Integer -Valid Range: Minimum value of 1\. -Required: No - - **Status** -The status of the allocation process\. -Type: String -Valid Values:` IN_PROGRESS | READY | FAILED` -Required: No - - **StatusReason** -For failed allocations, the reason that provisioned concurrency could not be allocated\. -Type: String -Required: No - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/ProvisionedConcurrencyConfigListItem) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/ProvisionedConcurrencyConfigListItem) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/ProvisionedConcurrencyConfigListItem) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/ProvisionedConcurrencyConfigListItem) \ No newline at end of file diff --git a/doc_source/API_PublishLayerVersion.md b/doc_source/API_PublishLayerVersion.md deleted file mode 100644 index 906b7da0..00000000 --- a/doc_source/API_PublishLayerVersion.md +++ /dev/null @@ -1,167 +0,0 @@ -# PublishLayerVersion - -Creates an [AWS Lambda layer](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) from a ZIP archive\. Each time you call `PublishLayerVersion` with the same layer name, a new version is created\. - -Add layers to your function with [CreateFunction](API_CreateFunction.md) or [UpdateFunctionConfiguration](API_UpdateFunctionConfiguration.md)\. - -## Request Syntax - -``` -POST /2018-10-31/layers/LayerName/versions HTTP/1.1 -Content-type: application/json - -{ - "[CompatibleRuntimes](#SSS-PublishLayerVersion-request-CompatibleRuntimes)": [ "string" ], - "[Content](#SSS-PublishLayerVersion-request-Content)": { - "[S3Bucket](API_LayerVersionContentInput.md#SSS-Type-LayerVersionContentInput-S3Bucket)": "string", - "[S3Key](API_LayerVersionContentInput.md#SSS-Type-LayerVersionContentInput-S3Key)": "string", - "[S3ObjectVersion](API_LayerVersionContentInput.md#SSS-Type-LayerVersionContentInput-S3ObjectVersion)": "string", - "[ZipFile](API_LayerVersionContentInput.md#SSS-Type-LayerVersionContentInput-ZipFile)": blob - }, - "[Description](#SSS-PublishLayerVersion-request-Description)": "string", - "[LicenseInfo](#SSS-PublishLayerVersion-request-LicenseInfo)": "string" -} -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [LayerName](#API_PublishLayerVersion_RequestSyntax) ** -The name or Amazon Resource Name \(ARN\) of the layer\. -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:[a-zA-Z0-9-]+:lambda:[a-zA-Z0-9-]+:\d{12}:layer:[a-zA-Z0-9-_]+)|[a-zA-Z0-9-_]+` - -## Request Body - -The request accepts the following data in JSON format\. - - ** [CompatibleRuntimes](#API_PublishLayerVersion_RequestSyntax) ** -A list of compatible [function runtimes](https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html)\. Used for filtering with [ListLayers](API_ListLayers.md) and [ListLayerVersions](API_ListLayerVersions.md)\. -Type: Array of strings -Array Members: Maximum number of 5 items\. -Valid Values:` nodejs10.x | nodejs12.x | java8 | java11 | python2.7 | python3.6 | python3.7 | python3.8 | dotnetcore2.1 | go1.x | ruby2.5 | ruby2.7 | provided` -Required: No - - ** [Content](#API_PublishLayerVersion_RequestSyntax) ** -The function layer archive\. -Type: [LayerVersionContentInput](API_LayerVersionContentInput.md) object -Required: Yes - - ** [Description](#API_PublishLayerVersion_RequestSyntax) ** -The description of the version\. -Type: String -Length Constraints: Minimum length of 0\. Maximum length of 256\. -Required: No - - ** [LicenseInfo](#API_PublishLayerVersion_RequestSyntax) ** -The layer's software license\. It can be any of the following: -+ An [SPDX license identifier](https://spdx.org/licenses/)\. For example, `MIT`\. -+ The URL of a license hosted on the internet\. For example, `https://opensource.org/licenses/MIT`\. -+ The full text of the license\. -Type: String -Length Constraints: Maximum length of 512\. -Required: No - -## Response Syntax - -``` -HTTP/1.1 201 -Content-type: application/json - -{ - "[CompatibleRuntimes](#SSS-PublishLayerVersion-response-CompatibleRuntimes)": [ "string" ], - "[Content](#SSS-PublishLayerVersion-response-Content)": { - "[CodeSha256](API_LayerVersionContentOutput.md#SSS-Type-LayerVersionContentOutput-CodeSha256)": "string", - "[CodeSize](API_LayerVersionContentOutput.md#SSS-Type-LayerVersionContentOutput-CodeSize)": number, - "[Location](API_LayerVersionContentOutput.md#SSS-Type-LayerVersionContentOutput-Location)": "string" - }, - "[CreatedDate](#SSS-PublishLayerVersion-response-CreatedDate)": "string", - "[Description](#SSS-PublishLayerVersion-response-Description)": "string", - "[LayerArn](#SSS-PublishLayerVersion-response-LayerArn)": "string", - "[LayerVersionArn](#SSS-PublishLayerVersion-response-LayerVersionArn)": "string", - "[LicenseInfo](#SSS-PublishLayerVersion-response-LicenseInfo)": "string", - "[Version](#SSS-PublishLayerVersion-response-Version)": number -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 201 response\. - -The following data is returned in JSON format by the service\. - - ** [CompatibleRuntimes](#API_PublishLayerVersion_ResponseSyntax) ** -The layer's compatible runtimes\. -Type: Array of strings -Array Members: Maximum number of 5 items\. -Valid Values:` nodejs10.x | nodejs12.x | java8 | java11 | python2.7 | python3.6 | python3.7 | python3.8 | dotnetcore2.1 | go1.x | ruby2.5 | ruby2.7 | provided` - - ** [Content](#API_PublishLayerVersion_ResponseSyntax) ** -Details about the layer version\. -Type: [LayerVersionContentOutput](API_LayerVersionContentOutput.md) object - - ** [CreatedDate](#API_PublishLayerVersion_ResponseSyntax) ** -The date that the layer version was created, in [ISO\-8601 format](https://www.w3.org/TR/NOTE-datetime) \(YYYY\-MM\-DDThh:mm:ss\.sTZD\)\. -Type: String - - ** [Description](#API_PublishLayerVersion_ResponseSyntax) ** -The description of the version\. -Type: String -Length Constraints: Minimum length of 0\. Maximum length of 256\. - - ** [LayerArn](#API_PublishLayerVersion_ResponseSyntax) ** -The ARN of the layer\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `arn:[a-zA-Z0-9-]+:lambda:[a-zA-Z0-9-]+:\d{12}:layer:[a-zA-Z0-9-_]+` - - ** [LayerVersionArn](#API_PublishLayerVersion_ResponseSyntax) ** -The ARN of the layer version\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `arn:[a-zA-Z0-9-]+:lambda:[a-zA-Z0-9-]+:\d{12}:layer:[a-zA-Z0-9-_]+:[0-9]+` - - ** [LicenseInfo](#API_PublishLayerVersion_ResponseSyntax) ** -The layer's software license\. -Type: String -Length Constraints: Maximum length of 512\. - - ** [Version](#API_PublishLayerVersion_ResponseSyntax) ** -The version number\. -Type: Long - -## Errors - - **CodeStorageExceededException** -You have exceeded your maximum total code size per account\. [Learn more](https://docs.aws.amazon.com/lambda/latest/dg/limits.html) -HTTP Status Code: 400 - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/PublishLayerVersion) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/PublishLayerVersion) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/PublishLayerVersion) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/PublishLayerVersion) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/PublishLayerVersion) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/PublishLayerVersion) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/PublishLayerVersion) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/PublishLayerVersion) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/PublishLayerVersion) \ No newline at end of file diff --git a/doc_source/API_PublishVersion.md b/doc_source/API_PublishVersion.md deleted file mode 100644 index 9b4d1580..00000000 --- a/doc_source/API_PublishVersion.md +++ /dev/null @@ -1,283 +0,0 @@ -# PublishVersion - -Creates a [version](https://docs.aws.amazon.com/lambda/latest/dg/versioning-aliases.html) from the current code and configuration of a function\. Use versions to create a snapshot of your function code and configuration that doesn't change\. - -AWS Lambda doesn't publish a version if the function's configuration and code haven't changed since the last version\. Use [UpdateFunctionCode](API_UpdateFunctionCode.md) or [UpdateFunctionConfiguration](API_UpdateFunctionConfiguration.md) to update the function before publishing a version\. - -Clients can invoke versions directly or with an alias\. To create an alias, use [CreateAlias](API_CreateAlias.md)\. - -## Request Syntax - -``` -POST /2015-03-31/functions/FunctionName/versions HTTP/1.1 -Content-type: application/json - -{ - "[CodeSha256](#SSS-PublishVersion-request-CodeSha256)": "string", - "[Description](#SSS-PublishVersion-request-Description)": "string", - "[RevisionId](#SSS-PublishVersion-request-RevisionId)": "string" -} -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [FunctionName](#API_PublishVersion_RequestSyntax) ** -The name of the Lambda function\. - -**Name formats** -+ **Function name** \- `MyFunction`\. -+ **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:MyFunction`\. -+ **Partial ARN** \- `123456789012:function:MyFunction`\. -The length constraint applies only to the full ARN\. If you specify only the function name, it is limited to 64 characters in length\. -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - -## Request Body - -The request accepts the following data in JSON format\. - - ** [CodeSha256](#API_PublishVersion_RequestSyntax) ** -Only publish a version if the hash value matches the value that's specified\. Use this option to avoid publishing a version if the function code has changed since you last updated it\. You can get the hash for the version that you uploaded from the output of [UpdateFunctionCode](API_UpdateFunctionCode.md)\. -Type: String -Required: No - - ** [Description](#API_PublishVersion_RequestSyntax) ** -A description for the version to override the description in the function configuration\. -Type: String -Length Constraints: Minimum length of 0\. Maximum length of 256\. -Required: No - - ** [RevisionId](#API_PublishVersion_RequestSyntax) ** -Only update the function if the revision ID matches the ID that's specified\. Use this option to avoid publishing a version if the function configuration has changed since you last updated it\. -Type: String -Required: No - -## Response Syntax - -``` -HTTP/1.1 201 -Content-type: application/json - -{ - "[CodeSha256](#SSS-PublishVersion-response-CodeSha256)": "string", - "[CodeSize](#SSS-PublishVersion-response-CodeSize)": number, - "[DeadLetterConfig](#SSS-PublishVersion-response-DeadLetterConfig)": { - "[TargetArn](API_DeadLetterConfig.md#SSS-Type-DeadLetterConfig-TargetArn)": "string" - }, - "[Description](#SSS-PublishVersion-response-Description)": "string", - "[Environment](#SSS-PublishVersion-response-Environment)": { - "[Error](API_EnvironmentResponse.md#SSS-Type-EnvironmentResponse-Error)": { - "[ErrorCode](API_EnvironmentError.md#SSS-Type-EnvironmentError-ErrorCode)": "string", - "[Message](API_EnvironmentError.md#SSS-Type-EnvironmentError-Message)": "string" - }, - "[Variables](API_EnvironmentResponse.md#SSS-Type-EnvironmentResponse-Variables)": { - "string" : "string" - } - }, - "[FunctionArn](#SSS-PublishVersion-response-FunctionArn)": "string", - "[FunctionName](#SSS-PublishVersion-response-FunctionName)": "string", - "[Handler](#SSS-PublishVersion-response-Handler)": "string", - "[KMSKeyArn](#SSS-PublishVersion-response-KMSKeyArn)": "string", - "[LastModified](#SSS-PublishVersion-response-LastModified)": "string", - "[LastUpdateStatus](#SSS-PublishVersion-response-LastUpdateStatus)": "string", - "[LastUpdateStatusReason](#SSS-PublishVersion-response-LastUpdateStatusReason)": "string", - "[LastUpdateStatusReasonCode](#SSS-PublishVersion-response-LastUpdateStatusReasonCode)": "string", - "[Layers](#SSS-PublishVersion-response-Layers)": [ - { - "[Arn](API_Layer.md#SSS-Type-Layer-Arn)": "string", - "[CodeSize](API_Layer.md#SSS-Type-Layer-CodeSize)": number - } - ], - "[MasterArn](#SSS-PublishVersion-response-MasterArn)": "string", - "[MemorySize](#SSS-PublishVersion-response-MemorySize)": number, - "[RevisionId](#SSS-PublishVersion-response-RevisionId)": "string", - "[Role](#SSS-PublishVersion-response-Role)": "string", - "[Runtime](#SSS-PublishVersion-response-Runtime)": "string", - "[State](#SSS-PublishVersion-response-State)": "string", - "[StateReason](#SSS-PublishVersion-response-StateReason)": "string", - "[StateReasonCode](#SSS-PublishVersion-response-StateReasonCode)": "string", - "[Timeout](#SSS-PublishVersion-response-Timeout)": number, - "[TracingConfig](#SSS-PublishVersion-response-TracingConfig)": { - "[Mode](API_TracingConfigResponse.md#SSS-Type-TracingConfigResponse-Mode)": "string" - }, - "[Version](#SSS-PublishVersion-response-Version)": "string", - "[VpcConfig](#SSS-PublishVersion-response-VpcConfig)": { - "[SecurityGroupIds](API_VpcConfigResponse.md#SSS-Type-VpcConfigResponse-SecurityGroupIds)": [ "string" ], - "[SubnetIds](API_VpcConfigResponse.md#SSS-Type-VpcConfigResponse-SubnetIds)": [ "string" ], - "[VpcId](API_VpcConfigResponse.md#SSS-Type-VpcConfigResponse-VpcId)": "string" - } -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 201 response\. - -The following data is returned in JSON format by the service\. - - ** [CodeSha256](#API_PublishVersion_ResponseSyntax) ** -The SHA256 hash of the function's deployment package\. -Type: String - - ** [CodeSize](#API_PublishVersion_ResponseSyntax) ** -The size of the function's deployment package, in bytes\. -Type: Long - - ** [DeadLetterConfig](#API_PublishVersion_ResponseSyntax) ** -The function's dead letter queue\. -Type: [DeadLetterConfig](API_DeadLetterConfig.md) object - - ** [Description](#API_PublishVersion_ResponseSyntax) ** -The function's description\. -Type: String -Length Constraints: Minimum length of 0\. Maximum length of 256\. - - ** [Environment](#API_PublishVersion_ResponseSyntax) ** -The function's environment variables\. -Type: [EnvironmentResponse](API_EnvironmentResponse.md) object - - ** [FunctionArn](#API_PublishVersion_ResponseSyntax) ** -The function's Amazon Resource Name \(ARN\)\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}(-gov)?-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_\.]+(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [FunctionName](#API_PublishVersion_ResponseSyntax) ** -The name of the function\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 170\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_\.]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [Handler](#API_PublishVersion_ResponseSyntax) ** -The function that Lambda calls to begin executing your function\. -Type: String -Length Constraints: Maximum length of 128\. -Pattern: `[^\s]+` - - ** [KMSKeyArn](#API_PublishVersion_ResponseSyntax) ** -The KMS key that's used to encrypt the function's environment variables\. This key is only returned if you've configured a customer managed CMK\. -Type: String -Pattern: `(arn:(aws[a-zA-Z-]*)?:[a-z0-9-.]+:.*)|()` - - ** [LastModified](#API_PublishVersion_ResponseSyntax) ** -The date and time that the function was last updated, in [ISO\-8601 format](https://www.w3.org/TR/NOTE-datetime) \(YYYY\-MM\-DDThh:mm:ss\.sTZD\)\. -Type: String - - ** [LastUpdateStatus](#API_PublishVersion_ResponseSyntax) ** -The status of the last update that was performed on the function\. This is first set to `Successful` after function creation completes\. -Type: String -Valid Values:` Successful | Failed | InProgress` - - ** [LastUpdateStatusReason](#API_PublishVersion_ResponseSyntax) ** -The reason for the last update that was performed on the function\. -Type: String - - ** [LastUpdateStatusReasonCode](#API_PublishVersion_ResponseSyntax) ** -The reason code for the last update that was performed on the function\. -Type: String -Valid Values:` EniLimitExceeded | InsufficientRolePermissions | InvalidConfiguration | InternalError | SubnetOutOfIPAddresses | InvalidSubnet | InvalidSecurityGroup` - - ** [Layers](#API_PublishVersion_ResponseSyntax) ** -The function's [ layers](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)\. -Type: Array of [Layer](API_Layer.md) objects - - ** [MasterArn](#API_PublishVersion_ResponseSyntax) ** -For Lambda@Edge functions, the ARN of the master function\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}(-gov)?-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [MemorySize](#API_PublishVersion_ResponseSyntax) ** -The memory that's allocated to the function\. -Type: Integer -Valid Range: Minimum value of 128\. Maximum value of 3008\. - - ** [RevisionId](#API_PublishVersion_ResponseSyntax) ** -The latest updated revision of the function or alias\. -Type: String - - ** [Role](#API_PublishVersion_ResponseSyntax) ** -The function's execution role\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:iam::\d{12}:role/?[a-zA-Z_0-9+=,.@\-_/]+` - - ** [Runtime](#API_PublishVersion_ResponseSyntax) ** -The runtime environment for the Lambda function\. -Type: String -Valid Values:` nodejs10.x | nodejs12.x | java8 | java11 | python2.7 | python3.6 | python3.7 | python3.8 | dotnetcore2.1 | go1.x | ruby2.5 | ruby2.7 | provided` - - ** [State](#API_PublishVersion_ResponseSyntax) ** -The current state of the function\. When the state is `Inactive`, you can reactivate the function by invoking it\. -Type: String -Valid Values:` Pending | Active | Inactive | Failed` - - ** [StateReason](#API_PublishVersion_ResponseSyntax) ** -The reason for the function's current state\. -Type: String - - ** [StateReasonCode](#API_PublishVersion_ResponseSyntax) ** -The reason code for the function's current state\. When the code is `Creating`, you can't invoke or modify the function\. -Type: String -Valid Values:` Idle | Creating | Restoring | EniLimitExceeded | InsufficientRolePermissions | InvalidConfiguration | InternalError | SubnetOutOfIPAddresses | InvalidSubnet | InvalidSecurityGroup` - - ** [Timeout](#API_PublishVersion_ResponseSyntax) ** -The amount of time that Lambda allows a function to run before stopping it\. -Type: Integer -Valid Range: Minimum value of 1\. - - ** [TracingConfig](#API_PublishVersion_ResponseSyntax) ** -The function's AWS X\-Ray tracing configuration\. -Type: [TracingConfigResponse](API_TracingConfigResponse.md) object - - ** [Version](#API_PublishVersion_ResponseSyntax) ** -The version of the Lambda function\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 1024\. -Pattern: `(\$LATEST|[0-9]+)` - - ** [VpcConfig](#API_PublishVersion_ResponseSyntax) ** -The function's networking configuration\. -Type: [VpcConfigResponse](API_VpcConfigResponse.md) object - -## Errors - - **CodeStorageExceededException** -You have exceeded your maximum total code size per account\. [Learn more](https://docs.aws.amazon.com/lambda/latest/dg/limits.html) -HTTP Status Code: 400 - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **PreconditionFailedException** -The RevisionId provided does not match the latest RevisionId for the Lambda function or alias\. Call the `GetFunction` or the `GetAlias` API to retrieve the latest RevisionId for your resource\. -HTTP Status Code: 412 - - **ResourceConflictException** -The resource already exists, or another operation is in progress\. -HTTP Status Code: 409 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/PublishVersion) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/PublishVersion) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/PublishVersion) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/PublishVersion) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/PublishVersion) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/PublishVersion) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/PublishVersion) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/PublishVersion) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/PublishVersion) \ No newline at end of file diff --git a/doc_source/API_PutFunctionConcurrency.md b/doc_source/API_PutFunctionConcurrency.md deleted file mode 100644 index 2c10afe3..00000000 --- a/doc_source/API_PutFunctionConcurrency.md +++ /dev/null @@ -1,100 +0,0 @@ -# PutFunctionConcurrency - -Sets the maximum number of simultaneous executions for a function, and reserves capacity for that concurrency level\. - -Concurrency settings apply to the function as a whole, including all published versions and the unpublished version\. Reserving concurrency both ensures that your function has capacity to process the specified number of events simultaneously, and prevents it from scaling beyond that level\. Use [GetFunction](API_GetFunction.md) to see the current setting for a function\. - -Use [GetAccountSettings](API_GetAccountSettings.md) to see your Regional concurrency limit\. You can reserve concurrency for as many functions as you like, as long as you leave at least 100 simultaneous executions unreserved for functions that aren't configured with a per\-function limit\. For more information, see [Managing Concurrency](https://docs.aws.amazon.com/lambda/latest/dg/concurrent-executions.html)\. - -## Request Syntax - -``` -PUT /2017-10-31/functions/FunctionName/concurrency HTTP/1.1 -Content-type: application/json - -{ - "[ReservedConcurrentExecutions](#SSS-PutFunctionConcurrency-request-ReservedConcurrentExecutions)": number -} -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [FunctionName](#API_PutFunctionConcurrency_RequestSyntax) ** -The name of the Lambda function\. - -**Name formats** -+ **Function name** \- `my-function`\. -+ **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:my-function`\. -+ **Partial ARN** \- `123456789012:function:my-function`\. -The length constraint applies only to the full ARN\. If you specify only the function name, it is limited to 64 characters in length\. -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - -## Request Body - -The request accepts the following data in JSON format\. - - ** [ReservedConcurrentExecutions](#API_PutFunctionConcurrency_RequestSyntax) ** -The number of simultaneous executions to reserve for the function\. -Type: Integer -Valid Range: Minimum value of 0\. -Required: Yes - -## Response Syntax - -``` -HTTP/1.1 200 -Content-type: application/json - -{ - "[ReservedConcurrentExecutions](#SSS-PutFunctionConcurrency-response-ReservedConcurrentExecutions)": number -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 200 response\. - -The following data is returned in JSON format by the service\. - - ** [ReservedConcurrentExecutions](#API_PutFunctionConcurrency_ResponseSyntax) ** -The number of concurrent executions that are reserved for this function\. For more information, see [Managing Concurrency](https://docs.aws.amazon.com/lambda/latest/dg/concurrent-executions.html)\. -Type: Integer -Valid Range: Minimum value of 0\. - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceConflictException** -The resource already exists, or another operation is in progress\. -HTTP Status Code: 409 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/PutFunctionConcurrency) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/PutFunctionConcurrency) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/PutFunctionConcurrency) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/PutFunctionConcurrency) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/PutFunctionConcurrency) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/PutFunctionConcurrency) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/PutFunctionConcurrency) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/PutFunctionConcurrency) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/PutFunctionConcurrency) \ No newline at end of file diff --git a/doc_source/API_PutFunctionEventInvokeConfig.md b/doc_source/API_PutFunctionEventInvokeConfig.md deleted file mode 100644 index 964b288b..00000000 --- a/doc_source/API_PutFunctionEventInvokeConfig.md +++ /dev/null @@ -1,162 +0,0 @@ -# PutFunctionEventInvokeConfig - -Configures options for [asynchronous invocation](https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html) on a function, version, or alias\. If a configuration already exists for a function, version, or alias, this operation overwrites it\. If you exclude any settings, they are removed\. To set one option without affecting existing settings for other options, use [PutFunctionEventInvokeConfig](#API_PutFunctionEventInvokeConfig)\. - -By default, Lambda retries an asynchronous invocation twice if the function returns an error\. It retains events in a queue for up to six hours\. When an event fails all processing attempts or stays in the asynchronous invocation queue for too long, Lambda discards it\. To retain discarded events, configure a dead\-letter queue with [UpdateFunctionConfiguration](API_UpdateFunctionConfiguration.md)\. - -To send an invocation record to a queue, topic, function, or event bus, specify a [destination](https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html#invocation-async-destinations)\. You can configure separate destinations for successful invocations \(on\-success\) and events that fail all processing attempts \(on\-failure\)\. You can configure destinations in addition to or instead of a dead\-letter queue\. - -## Request Syntax - -``` -PUT /2019-09-25/functions/FunctionName/event-invoke-config?Qualifier=Qualifier HTTP/1.1 -Content-type: application/json - -{ - "[DestinationConfig](#SSS-PutFunctionEventInvokeConfig-request-DestinationConfig)": { - "[OnFailure](API_DestinationConfig.md#SSS-Type-DestinationConfig-OnFailure)": { - "[Destination](API_OnFailure.md#SSS-Type-OnFailure-Destination)": "string" - }, - "[OnSuccess](API_DestinationConfig.md#SSS-Type-DestinationConfig-OnSuccess)": { - "[Destination](API_OnSuccess.md#SSS-Type-OnSuccess-Destination)": "string" - } - }, - "[MaximumEventAgeInSeconds](#SSS-PutFunctionEventInvokeConfig-request-MaximumEventAgeInSeconds)": number, - "[MaximumRetryAttempts](#SSS-PutFunctionEventInvokeConfig-request-MaximumRetryAttempts)": number -} -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [FunctionName](#API_PutFunctionEventInvokeConfig_RequestSyntax) ** -The name of the Lambda function, version, or alias\. - -**Name formats** -+ **Function name** \- `my-function` \(name\-only\), `my-function:v1` \(with alias\)\. -+ **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:my-function`\. -+ **Partial ARN** \- `123456789012:function:my-function`\. -You can append a version number or alias to any of the formats\. The length constraint applies only to the full ARN\. If you specify only the function name, it is limited to 64 characters in length\. -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [Qualifier](#API_PutFunctionEventInvokeConfig_RequestSyntax) ** -A version number or alias name\. -Length Constraints: Minimum length of 1\. Maximum length of 128\. -Pattern: `(|[a-zA-Z0-9$_-]+)` - -## Request Body - -The request accepts the following data in JSON format\. - - ** [DestinationConfig](#API_PutFunctionEventInvokeConfig_RequestSyntax) ** -A destination for events after they have been sent to a function for processing\. - -**Destinations** -+ **Function** \- The Amazon Resource Name \(ARN\) of a Lambda function\. -+ **Queue** \- The ARN of an SQS queue\. -+ **Topic** \- The ARN of an SNS topic\. -+ **Event Bus** \- The ARN of an Amazon EventBridge event bus\. -Type: [DestinationConfig](API_DestinationConfig.md) object -Required: No - - ** [MaximumEventAgeInSeconds](#API_PutFunctionEventInvokeConfig_RequestSyntax) ** -The maximum age of a request that Lambda sends to a function for processing\. -Type: Integer -Valid Range: Minimum value of 60\. Maximum value of 21600\. -Required: No - - ** [MaximumRetryAttempts](#API_PutFunctionEventInvokeConfig_RequestSyntax) ** -The maximum number of times to retry when the function returns an error\. -Type: Integer -Valid Range: Minimum value of 0\. Maximum value of 2\. -Required: No - -## Response Syntax - -``` -HTTP/1.1 200 -Content-type: application/json - -{ - "[DestinationConfig](#SSS-PutFunctionEventInvokeConfig-response-DestinationConfig)": { - "[OnFailure](API_DestinationConfig.md#SSS-Type-DestinationConfig-OnFailure)": { - "[Destination](API_OnFailure.md#SSS-Type-OnFailure-Destination)": "string" - }, - "[OnSuccess](API_DestinationConfig.md#SSS-Type-DestinationConfig-OnSuccess)": { - "[Destination](API_OnSuccess.md#SSS-Type-OnSuccess-Destination)": "string" - } - }, - "[FunctionArn](#SSS-PutFunctionEventInvokeConfig-response-FunctionArn)": "string", - "[LastModified](#SSS-PutFunctionEventInvokeConfig-response-LastModified)": number, - "[MaximumEventAgeInSeconds](#SSS-PutFunctionEventInvokeConfig-response-MaximumEventAgeInSeconds)": number, - "[MaximumRetryAttempts](#SSS-PutFunctionEventInvokeConfig-response-MaximumRetryAttempts)": number -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 200 response\. - -The following data is returned in JSON format by the service\. - - ** [DestinationConfig](#API_PutFunctionEventInvokeConfig_ResponseSyntax) ** -A destination for events after they have been sent to a function for processing\. - -**Destinations** -+ **Function** \- The Amazon Resource Name \(ARN\) of a Lambda function\. -+ **Queue** \- The ARN of an SQS queue\. -+ **Topic** \- The ARN of an SNS topic\. -+ **Event Bus** \- The ARN of an Amazon EventBridge event bus\. -Type: [DestinationConfig](API_DestinationConfig.md) object - - ** [FunctionArn](#API_PutFunctionEventInvokeConfig_ResponseSyntax) ** -The Amazon Resource Name \(ARN\) of the function\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}(-gov)?-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [LastModified](#API_PutFunctionEventInvokeConfig_ResponseSyntax) ** -The date and time that the configuration was last updated, in Unix time seconds\. -Type: Timestamp - - ** [MaximumEventAgeInSeconds](#API_PutFunctionEventInvokeConfig_ResponseSyntax) ** -The maximum age of a request that Lambda sends to a function for processing\. -Type: Integer -Valid Range: Minimum value of 60\. Maximum value of 21600\. - - ** [MaximumRetryAttempts](#API_PutFunctionEventInvokeConfig_ResponseSyntax) ** -The maximum number of times to retry when the function returns an error\. -Type: Integer -Valid Range: Minimum value of 0\. Maximum value of 2\. - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/PutFunctionEventInvokeConfig) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/PutFunctionEventInvokeConfig) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/PutFunctionEventInvokeConfig) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/PutFunctionEventInvokeConfig) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/PutFunctionEventInvokeConfig) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/PutFunctionEventInvokeConfig) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/PutFunctionEventInvokeConfig) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/PutFunctionEventInvokeConfig) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/PutFunctionEventInvokeConfig) \ No newline at end of file diff --git a/doc_source/API_PutProvisionedConcurrencyConfig.md b/doc_source/API_PutProvisionedConcurrencyConfig.md deleted file mode 100644 index 4836442f..00000000 --- a/doc_source/API_PutProvisionedConcurrencyConfig.md +++ /dev/null @@ -1,129 +0,0 @@ -# PutProvisionedConcurrencyConfig - -Adds a provisioned concurrency configuration to a function's alias or version\. - -## Request Syntax - -``` -PUT /2019-09-30/functions/FunctionName/provisioned-concurrency?Qualifier=Qualifier HTTP/1.1 -Content-type: application/json - -{ - "[ProvisionedConcurrentExecutions](#SSS-PutProvisionedConcurrencyConfig-request-ProvisionedConcurrentExecutions)": number -} -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [FunctionName](#API_PutProvisionedConcurrencyConfig_RequestSyntax) ** -The name of the Lambda function\. - -**Name formats** -+ **Function name** \- `my-function`\. -+ **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:my-function`\. -+ **Partial ARN** \- `123456789012:function:my-function`\. -The length constraint applies only to the full ARN\. If you specify only the function name, it is limited to 64 characters in length\. -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [Qualifier](#API_PutProvisionedConcurrencyConfig_RequestSyntax) ** -The version number or alias name\. -Length Constraints: Minimum length of 1\. Maximum length of 128\. -Pattern: `(|[a-zA-Z0-9$_-]+)` - -## Request Body - -The request accepts the following data in JSON format\. - - ** [ProvisionedConcurrentExecutions](#API_PutProvisionedConcurrencyConfig_RequestSyntax) ** -The amount of provisioned concurrency to allocate for the version or alias\. -Type: Integer -Valid Range: Minimum value of 1\. -Required: Yes - -## Response Syntax - -``` -HTTP/1.1 202 -Content-type: application/json - -{ - "[AllocatedProvisionedConcurrentExecutions](#SSS-PutProvisionedConcurrencyConfig-response-AllocatedProvisionedConcurrentExecutions)": number, - "[AvailableProvisionedConcurrentExecutions](#SSS-PutProvisionedConcurrencyConfig-response-AvailableProvisionedConcurrentExecutions)": number, - "[LastModified](#SSS-PutProvisionedConcurrencyConfig-response-LastModified)": "string", - "[RequestedProvisionedConcurrentExecutions](#SSS-PutProvisionedConcurrencyConfig-response-RequestedProvisionedConcurrentExecutions)": number, - "[Status](#SSS-PutProvisionedConcurrencyConfig-response-Status)": "string", - "[StatusReason](#SSS-PutProvisionedConcurrencyConfig-response-StatusReason)": "string" -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 202 response\. - -The following data is returned in JSON format by the service\. - - ** [AllocatedProvisionedConcurrentExecutions](#API_PutProvisionedConcurrencyConfig_ResponseSyntax) ** -The amount of provisioned concurrency allocated\. -Type: Integer -Valid Range: Minimum value of 0\. - - ** [AvailableProvisionedConcurrentExecutions](#API_PutProvisionedConcurrencyConfig_ResponseSyntax) ** -The amount of provisioned concurrency available\. -Type: Integer -Valid Range: Minimum value of 0\. - - ** [LastModified](#API_PutProvisionedConcurrencyConfig_ResponseSyntax) ** -The date and time that a user last updated the configuration, in [ISO 8601 format](https://www.iso.org/iso-8601-date-and-time-format.html)\. -Type: String - - ** [RequestedProvisionedConcurrentExecutions](#API_PutProvisionedConcurrencyConfig_ResponseSyntax) ** -The amount of provisioned concurrency requested\. -Type: Integer -Valid Range: Minimum value of 1\. - - ** [Status](#API_PutProvisionedConcurrencyConfig_ResponseSyntax) ** -The status of the allocation process\. -Type: String -Valid Values:` IN_PROGRESS | READY | FAILED` - - ** [StatusReason](#API_PutProvisionedConcurrencyConfig_ResponseSyntax) ** -For failed allocations, the reason that provisioned concurrency could not be allocated\. -Type: String - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceConflictException** -The resource already exists, or another operation is in progress\. -HTTP Status Code: 409 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/PutProvisionedConcurrencyConfig) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/PutProvisionedConcurrencyConfig) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/PutProvisionedConcurrencyConfig) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/PutProvisionedConcurrencyConfig) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/PutProvisionedConcurrencyConfig) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/PutProvisionedConcurrencyConfig) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/PutProvisionedConcurrencyConfig) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/PutProvisionedConcurrencyConfig) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/PutProvisionedConcurrencyConfig) \ No newline at end of file diff --git a/doc_source/API_Reference.md b/doc_source/API_Reference.md deleted file mode 100644 index 23fef105..00000000 --- a/doc_source/API_Reference.md +++ /dev/null @@ -1,26 +0,0 @@ -# API reference - -This section contains the AWS Lambda API Reference documentation\. When making the API calls, you will need to authenticate your request by providing a signature\. AWS Lambda supports signature version 4\. For more information, see [Signature Version 4 signing process](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html) in the *Amazon Web Services General Reference*\. - -For an overview of the service, see [What is AWS Lambda?](welcome.md)\. - -You can use the AWS CLI to explore the AWS Lambda API\. This guide provides several tutorials that use the AWS CLI\. - -**Topics** -+ [Actions](API_Operations.md) -+ [Data Types](API_Types.md) - -## Certificate errors when using an SDK - -Because AWS SDKs use the CA certificates from your computer, changes to the certificates on the AWS servers can cause connection failures when you attempt to use an SDK\. You can prevent these failures by keeping your computer's CA certificates and operating system up\-to\-date\. If you encounter this issue in a corporate environment and do not manage your own computer, you might need to ask an administrator to assist with the update process\. The following list shows minimum operating system and Java versions: -+ Microsoft Windows versions that have updates from January 2005 or later installed contain at least one of the required CAs in their trust list\. -+ Mac OS X 10\.4 with Java for Mac OS X 10\.4 Release 5 \(February 2007\), Mac OS X 10\.5 \(October 2007\), and later versions contain at least one of the required CAs in their trust list\. -+ Red Hat Enterprise Linux 5 \(March 2007\), 6, and 7 and CentOS 5, 6, and 7 all contain at least one of the required CAs in their default trusted CA list\. -+ Java 1\.4\.2\_12 \(May 2006\), 5 Update 2 \(March 2005\), and all later versions, including Java 6 \(December 2006\), 7, and 8, contain at least one of the required CAs in their default trusted CA list\. - -When accessing the AWS Lambda management console or AWS Lambda API endpoints, whether through browsers or programmatically, you will need to ensure your client machines support any of the following CAs: -+ Amazon Root CA 1 -+ Starfield Services Root Certificate Authority \- G2 -+ Starfield Class 2 Certification Authority - -Root certificates from the first two authorities are available from [Amazon trust services](https://www.amazontrust.com/repository/), but keeping your computer up\-to\-date is the more straightforward solution\. To learn more about ACM\-provided certificates, see [AWS Certificate Manager FAQs\.](https://aws.amazon.com/certificate-manager/faqs/#certificates) \ No newline at end of file diff --git a/doc_source/API_RemoveLayerVersionPermission.md b/doc_source/API_RemoveLayerVersionPermission.md deleted file mode 100644 index b4fde1af..00000000 --- a/doc_source/API_RemoveLayerVersionPermission.md +++ /dev/null @@ -1,78 +0,0 @@ -# RemoveLayerVersionPermission - -Removes a statement from the permissions policy for a version of an [AWS Lambda layer](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)\. For more information, see [AddLayerVersionPermission](API_AddLayerVersionPermission.md)\. - -## Request Syntax - -``` -DELETE /2018-10-31/layers/LayerName/versions/VersionNumber/policy/StatementId?RevisionId=RevisionId HTTP/1.1 -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [LayerName](#API_RemoveLayerVersionPermission_RequestSyntax) ** -The name or Amazon Resource Name \(ARN\) of the layer\. -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:[a-zA-Z0-9-]+:lambda:[a-zA-Z0-9-]+:\d{12}:layer:[a-zA-Z0-9-_]+)|[a-zA-Z0-9-_]+` - - ** [RevisionId](#API_RemoveLayerVersionPermission_RequestSyntax) ** -Only update the policy if the revision ID matches the ID specified\. Use this option to avoid modifying a policy that has changed since you last read it\. - - ** [StatementId](#API_RemoveLayerVersionPermission_RequestSyntax) ** -The identifier that was specified when the statement was added\. -Length Constraints: Minimum length of 1\. Maximum length of 100\. -Pattern: `([a-zA-Z0-9-_]+)` - - ** [VersionNumber](#API_RemoveLayerVersionPermission_RequestSyntax) ** -The version number\. - -## Request Body - -The request does not have a request body\. - -## Response Syntax - -``` -HTTP/1.1 204 -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body\. - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **PreconditionFailedException** -The RevisionId provided does not match the latest RevisionId for the Lambda function or alias\. Call the `GetFunction` or the `GetAlias` API to retrieve the latest RevisionId for your resource\. -HTTP Status Code: 412 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/RemoveLayerVersionPermission) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/RemoveLayerVersionPermission) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/RemoveLayerVersionPermission) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/RemoveLayerVersionPermission) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/RemoveLayerVersionPermission) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/RemoveLayerVersionPermission) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/RemoveLayerVersionPermission) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/RemoveLayerVersionPermission) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/RemoveLayerVersionPermission) \ No newline at end of file diff --git a/doc_source/API_RemovePermission.md b/doc_source/API_RemovePermission.md deleted file mode 100644 index 470cd6e4..00000000 --- a/doc_source/API_RemovePermission.md +++ /dev/null @@ -1,86 +0,0 @@ -# RemovePermission - -Revokes function\-use permission from an AWS service or another account\. You can get the ID of the statement from the output of [GetPolicy](API_GetPolicy.md)\. - -## Request Syntax - -``` -DELETE /2015-03-31/functions/FunctionName/policy/StatementId?Qualifier=Qualifier&RevisionId=RevisionId HTTP/1.1 -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [FunctionName](#API_RemovePermission_RequestSyntax) ** -The name of the Lambda function, version, or alias\. - -**Name formats** -+ **Function name** \- `my-function` \(name\-only\), `my-function:v1` \(with alias\)\. -+ **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:my-function`\. -+ **Partial ARN** \- `123456789012:function:my-function`\. -You can append a version number or alias to any of the formats\. The length constraint applies only to the full ARN\. If you specify only the function name, it is limited to 64 characters in length\. -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [Qualifier](#API_RemovePermission_RequestSyntax) ** -Specify a version or alias to remove permissions from a published version of the function\. -Length Constraints: Minimum length of 1\. Maximum length of 128\. -Pattern: `(|[a-zA-Z0-9$_-]+)` - - ** [RevisionId](#API_RemovePermission_RequestSyntax) ** -Only update the policy if the revision ID matches the ID that's specified\. Use this option to avoid modifying a policy that has changed since you last read it\. - - ** [StatementId](#API_RemovePermission_RequestSyntax) ** -Statement ID of the permission to remove\. -Length Constraints: Minimum length of 1\. Maximum length of 100\. -Pattern: `([a-zA-Z0-9-_.]+)` - -## Request Body - -The request does not have a request body\. - -## Response Syntax - -``` -HTTP/1.1 204 -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body\. - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **PreconditionFailedException** -The RevisionId provided does not match the latest RevisionId for the Lambda function or alias\. Call the `GetFunction` or the `GetAlias` API to retrieve the latest RevisionId for your resource\. -HTTP Status Code: 412 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/RemovePermission) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/RemovePermission) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/RemovePermission) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/RemovePermission) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/RemovePermission) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/RemovePermission) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/RemovePermission) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/RemovePermission) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/RemovePermission) \ No newline at end of file diff --git a/doc_source/API_TagResource.md b/doc_source/API_TagResource.md deleted file mode 100644 index b16bb352..00000000 --- a/doc_source/API_TagResource.md +++ /dev/null @@ -1,78 +0,0 @@ -# TagResource - -Adds [tags](https://docs.aws.amazon.com/lambda/latest/dg/tagging.html) to a function\. - -## Request Syntax - -``` -POST /2017-03-31/tags/ARN HTTP/1.1 -Content-type: application/json - -{ - "[Tags](#SSS-TagResource-request-Tags)": { - "string" : "string" - } -} -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [ARN](#API_TagResource_RequestSyntax) ** -The function's Amazon Resource Name \(ARN\)\. -Pattern: `arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}(-gov)?-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?` - -## Request Body - -The request accepts the following data in JSON format\. - - ** [Tags](#API_TagResource_RequestSyntax) ** -A list of tags to apply to the function\. -Type: String to string map -Required: Yes - -## Response Syntax - -``` -HTTP/1.1 204 -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body\. - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceConflictException** -The resource already exists, or another operation is in progress\. -HTTP Status Code: 409 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/TagResource) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/TagResource) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/TagResource) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/TagResource) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/TagResource) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/TagResource) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/TagResource) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/TagResource) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/TagResource) \ No newline at end of file diff --git a/doc_source/API_TracingConfig.md b/doc_source/API_TracingConfig.md deleted file mode 100644 index 40bef909..00000000 --- a/doc_source/API_TracingConfig.md +++ /dev/null @@ -1,19 +0,0 @@ -# TracingConfig - -The function's AWS X\-Ray tracing configuration\. To sample and record incoming requests, set `Mode` to `Active`\. - -## Contents - - **Mode** -The tracing mode\. -Type: String -Valid Values:` Active | PassThrough` -Required: No - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/TracingConfig) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/TracingConfig) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/TracingConfig) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/TracingConfig) \ No newline at end of file diff --git a/doc_source/API_TracingConfigResponse.md b/doc_source/API_TracingConfigResponse.md deleted file mode 100644 index 97f01023..00000000 --- a/doc_source/API_TracingConfigResponse.md +++ /dev/null @@ -1,19 +0,0 @@ -# TracingConfigResponse - -The function's AWS X\-Ray tracing configuration\. - -## Contents - - **Mode** -The tracing mode\. -Type: String -Valid Values:` Active | PassThrough` -Required: No - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/TracingConfigResponse) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/TracingConfigResponse) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/TracingConfigResponse) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/TracingConfigResponse) \ No newline at end of file diff --git a/doc_source/API_Types.md b/doc_source/API_Types.md deleted file mode 100644 index b8e837b4..00000000 --- a/doc_source/API_Types.md +++ /dev/null @@ -1,30 +0,0 @@ -# Data Types - -The following data types are supported: -+ [AccountLimit](API_AccountLimit.md) -+ [AccountUsage](API_AccountUsage.md) -+ [AliasConfiguration](API_AliasConfiguration.md) -+ [AliasRoutingConfiguration](API_AliasRoutingConfiguration.md) -+ [Concurrency](API_Concurrency.md) -+ [DeadLetterConfig](API_DeadLetterConfig.md) -+ [DestinationConfig](API_DestinationConfig.md) -+ [Environment](API_Environment.md) -+ [EnvironmentError](API_EnvironmentError.md) -+ [EnvironmentResponse](API_EnvironmentResponse.md) -+ [EventSourceMappingConfiguration](API_EventSourceMappingConfiguration.md) -+ [FunctionCode](API_FunctionCode.md) -+ [FunctionCodeLocation](API_FunctionCodeLocation.md) -+ [FunctionConfiguration](API_FunctionConfiguration.md) -+ [FunctionEventInvokeConfig](API_FunctionEventInvokeConfig.md) -+ [Layer](API_Layer.md) -+ [LayersListItem](API_LayersListItem.md) -+ [LayerVersionContentInput](API_LayerVersionContentInput.md) -+ [LayerVersionContentOutput](API_LayerVersionContentOutput.md) -+ [LayerVersionsListItem](API_LayerVersionsListItem.md) -+ [OnFailure](API_OnFailure.md) -+ [OnSuccess](API_OnSuccess.md) -+ [ProvisionedConcurrencyConfigListItem](API_ProvisionedConcurrencyConfigListItem.md) -+ [TracingConfig](API_TracingConfig.md) -+ [TracingConfigResponse](API_TracingConfigResponse.md) -+ [VpcConfig](API_VpcConfig.md) -+ [VpcConfigResponse](API_VpcConfigResponse.md) \ No newline at end of file diff --git a/doc_source/API_UntagResource.md b/doc_source/API_UntagResource.md deleted file mode 100644 index 124b1940..00000000 --- a/doc_source/API_UntagResource.md +++ /dev/null @@ -1,69 +0,0 @@ -# UntagResource - -Removes [tags](https://docs.aws.amazon.com/lambda/latest/dg/tagging.html) from a function\. - -## Request Syntax - -``` -DELETE /2017-03-31/tags/ARN?tagKeys=TagKeys HTTP/1.1 -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [ARN](#API_UntagResource_RequestSyntax) ** -The function's Amazon Resource Name \(ARN\)\. -Pattern: `arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}(-gov)?-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [TagKeys](#API_UntagResource_RequestSyntax) ** -A list of tag keys to remove from the function\. - -## Request Body - -The request does not have a request body\. - -## Response Syntax - -``` -HTTP/1.1 204 -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body\. - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceConflictException** -The resource already exists, or another operation is in progress\. -HTTP Status Code: 409 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/UntagResource) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/UntagResource) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/UntagResource) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/UntagResource) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/UntagResource) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/UntagResource) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/UntagResource) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/UntagResource) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/UntagResource) \ No newline at end of file diff --git a/doc_source/API_UpdateAlias.md b/doc_source/API_UpdateAlias.md deleted file mode 100644 index cfc2d8ac..00000000 --- a/doc_source/API_UpdateAlias.md +++ /dev/null @@ -1,163 +0,0 @@ -# UpdateAlias - -Updates the configuration of a Lambda function [alias](https://docs.aws.amazon.com/lambda/latest/dg/versioning-aliases.html)\. - -## Request Syntax - -``` -PUT /2015-03-31/functions/FunctionName/aliases/Name HTTP/1.1 -Content-type: application/json - -{ - "[Description](#SSS-UpdateAlias-request-Description)": "string", - "[FunctionVersion](#SSS-UpdateAlias-request-FunctionVersion)": "string", - "[RevisionId](#SSS-UpdateAlias-request-RevisionId)": "string", - "[RoutingConfig](#SSS-UpdateAlias-request-RoutingConfig)": { - "[AdditionalVersionWeights](API_AliasRoutingConfiguration.md#SSS-Type-AliasRoutingConfiguration-AdditionalVersionWeights)": { - "string" : number - } - } -} -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [FunctionName](#API_UpdateAlias_RequestSyntax) ** -The name of the Lambda function\. - -**Name formats** -+ **Function name** \- `MyFunction`\. -+ **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:MyFunction`\. -+ **Partial ARN** \- `123456789012:function:MyFunction`\. -The length constraint applies only to the full ARN\. If you specify only the function name, it is limited to 64 characters in length\. -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [Name](#API_UpdateAlias_RequestSyntax) ** -The name of the alias\. -Length Constraints: Minimum length of 1\. Maximum length of 128\. -Pattern: `(?!^[0-9]+$)([a-zA-Z0-9-_]+)` - -## Request Body - -The request accepts the following data in JSON format\. - - ** [Description](#API_UpdateAlias_RequestSyntax) ** -A description of the alias\. -Type: String -Length Constraints: Minimum length of 0\. Maximum length of 256\. -Required: No - - ** [FunctionVersion](#API_UpdateAlias_RequestSyntax) ** -The function version that the alias invokes\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 1024\. -Pattern: `(\$LATEST|[0-9]+)` -Required: No - - ** [RevisionId](#API_UpdateAlias_RequestSyntax) ** -Only update the alias if the revision ID matches the ID that's specified\. Use this option to avoid modifying an alias that has changed since you last read it\. -Type: String -Required: No - - ** [RoutingConfig](#API_UpdateAlias_RequestSyntax) ** -The [routing configuration](https://docs.aws.amazon.com/lambda/latest/dg/lambda-traffic-shifting-using-aliases.html) of the alias\. -Type: [AliasRoutingConfiguration](API_AliasRoutingConfiguration.md) object -Required: No - -## Response Syntax - -``` -HTTP/1.1 200 -Content-type: application/json - -{ - "[AliasArn](#SSS-UpdateAlias-response-AliasArn)": "string", - "[Description](#SSS-UpdateAlias-response-Description)": "string", - "[FunctionVersion](#SSS-UpdateAlias-response-FunctionVersion)": "string", - "[Name](#SSS-UpdateAlias-response-Name)": "string", - "[RevisionId](#SSS-UpdateAlias-response-RevisionId)": "string", - "[RoutingConfig](#SSS-UpdateAlias-response-RoutingConfig)": { - "[AdditionalVersionWeights](API_AliasRoutingConfiguration.md#SSS-Type-AliasRoutingConfiguration-AdditionalVersionWeights)": { - "string" : number - } - } -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 200 response\. - -The following data is returned in JSON format by the service\. - - ** [AliasArn](#API_UpdateAlias_ResponseSyntax) ** -The Amazon Resource Name \(ARN\) of the alias\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}(-gov)?-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [Description](#API_UpdateAlias_ResponseSyntax) ** -A description of the alias\. -Type: String -Length Constraints: Minimum length of 0\. Maximum length of 256\. - - ** [FunctionVersion](#API_UpdateAlias_ResponseSyntax) ** -The function version that the alias invokes\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 1024\. -Pattern: `(\$LATEST|[0-9]+)` - - ** [Name](#API_UpdateAlias_ResponseSyntax) ** -The name of the alias\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 128\. -Pattern: `(?!^[0-9]+$)([a-zA-Z0-9-_]+)` - - ** [RevisionId](#API_UpdateAlias_ResponseSyntax) ** -A unique identifier that changes when you update the alias\. -Type: String - - ** [RoutingConfig](#API_UpdateAlias_ResponseSyntax) ** -The [routing configuration](https://docs.aws.amazon.com/lambda/latest/dg/lambda-traffic-shifting-using-aliases.html) of the alias\. -Type: [AliasRoutingConfiguration](API_AliasRoutingConfiguration.md) object - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **PreconditionFailedException** -The RevisionId provided does not match the latest RevisionId for the Lambda function or alias\. Call the `GetFunction` or the `GetAlias` API to retrieve the latest RevisionId for your resource\. -HTTP Status Code: 412 - - **ResourceConflictException** -The resource already exists, or another operation is in progress\. -HTTP Status Code: 409 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/UpdateAlias) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/UpdateAlias) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/UpdateAlias) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/UpdateAlias) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/UpdateAlias) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/UpdateAlias) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/UpdateAlias) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/UpdateAlias) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/UpdateAlias) \ No newline at end of file diff --git a/doc_source/API_UpdateEventSourceMapping.md b/doc_source/API_UpdateEventSourceMapping.md deleted file mode 100644 index 9f9484a5..00000000 --- a/doc_source/API_UpdateEventSourceMapping.md +++ /dev/null @@ -1,248 +0,0 @@ -# UpdateEventSourceMapping - -Updates an event source mapping\. You can change the function that AWS Lambda invokes, or pause invocation and resume later from the same location\. - -The following error handling options are only available for stream sources \(DynamoDB and Kinesis\): -+ `BisectBatchOnFunctionError` \- If the function returns an error, split the batch in two and retry\. -+ `DestinationConfig` \- Send discarded records to an Amazon SQS queue or Amazon SNS topic\. -+ `MaximumRecordAgeInSeconds` \- Discard records older than the specified age\. -+ `MaximumRetryAttempts` \- Discard records after the specified number of retries\. -+ `ParallelizationFactor` \- Process multiple batches from each shard concurrently\. - -## Request Syntax - -``` -PUT /2015-03-31/event-source-mappings/UUID HTTP/1.1 -Content-type: application/json - -{ - "[BatchSize](#SSS-UpdateEventSourceMapping-request-BatchSize)": number, - "[BisectBatchOnFunctionError](#SSS-UpdateEventSourceMapping-request-BisectBatchOnFunctionError)": boolean, - "[DestinationConfig](#SSS-UpdateEventSourceMapping-request-DestinationConfig)": { - "[OnFailure](API_DestinationConfig.md#SSS-Type-DestinationConfig-OnFailure)": { - "[Destination](API_OnFailure.md#SSS-Type-OnFailure-Destination)": "string" - }, - "[OnSuccess](API_DestinationConfig.md#SSS-Type-DestinationConfig-OnSuccess)": { - "[Destination](API_OnSuccess.md#SSS-Type-OnSuccess-Destination)": "string" - } - }, - "[Enabled](#SSS-UpdateEventSourceMapping-request-Enabled)": boolean, - "[FunctionName](#SSS-UpdateEventSourceMapping-request-FunctionName)": "string", - "[MaximumBatchingWindowInSeconds](#SSS-UpdateEventSourceMapping-request-MaximumBatchingWindowInSeconds)": number, - "[MaximumRecordAgeInSeconds](#SSS-UpdateEventSourceMapping-request-MaximumRecordAgeInSeconds)": number, - "[MaximumRetryAttempts](#SSS-UpdateEventSourceMapping-request-MaximumRetryAttempts)": number, - "[ParallelizationFactor](#SSS-UpdateEventSourceMapping-request-ParallelizationFactor)": number -} -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [UUID](#API_UpdateEventSourceMapping_RequestSyntax) ** -The identifier of the event source mapping\. - -## Request Body - -The request accepts the following data in JSON format\. - - ** [BatchSize](#API_UpdateEventSourceMapping_RequestSyntax) ** -The maximum number of items to retrieve in a single batch\. -+ **Amazon Kinesis** \- Default 100\. Max 10,000\. -+ **Amazon DynamoDB Streams** \- Default 100\. Max 1,000\. -+ **Amazon Simple Queue Service** \- Default 10\. Max 10\. -Type: Integer -Valid Range: Minimum value of 1\. Maximum value of 10000\. -Required: No - - ** [BisectBatchOnFunctionError](#API_UpdateEventSourceMapping_RequestSyntax) ** -\(Streams\) If the function returns an error, split the batch in two and retry\. -Type: Boolean -Required: No - - ** [DestinationConfig](#API_UpdateEventSourceMapping_RequestSyntax) ** -\(Streams\) An Amazon SQS queue or Amazon SNS topic destination for discarded records\. -Type: [DestinationConfig](API_DestinationConfig.md) object -Required: No - - ** [Enabled](#API_UpdateEventSourceMapping_RequestSyntax) ** -Disables the event source mapping to pause polling and invocation\. -Type: Boolean -Required: No - - ** [FunctionName](#API_UpdateEventSourceMapping_RequestSyntax) ** -The name of the Lambda function\. - -**Name formats** -+ **Function name** \- `MyFunction`\. -+ **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:MyFunction`\. -+ **Version or Alias ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:MyFunction:PROD`\. -+ **Partial ARN** \- `123456789012:function:MyFunction`\. -The length constraint applies only to the full ARN\. If you specify only the function name, it's limited to 64 characters in length\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` -Required: No - - ** [MaximumBatchingWindowInSeconds](#API_UpdateEventSourceMapping_RequestSyntax) ** -\(Streams\) The maximum amount of time to gather records before invoking the function, in seconds\. -Type: Integer -Valid Range: Minimum value of 0\. Maximum value of 300\. -Required: No - - ** [MaximumRecordAgeInSeconds](#API_UpdateEventSourceMapping_RequestSyntax) ** -\(Streams\) The maximum age of a record that Lambda sends to a function for processing\. -Type: Integer -Valid Range: Minimum value of 60\. Maximum value of 604800\. -Required: No - - ** [MaximumRetryAttempts](#API_UpdateEventSourceMapping_RequestSyntax) ** -\(Streams\) The maximum number of times to retry when the function returns an error\. -Type: Integer -Valid Range: Minimum value of 0\. Maximum value of 10000\. -Required: No - - ** [ParallelizationFactor](#API_UpdateEventSourceMapping_RequestSyntax) ** -\(Streams\) The number of batches to process from each shard concurrently\. -Type: Integer -Valid Range: Minimum value of 1\. Maximum value of 10\. -Required: No - -## Response Syntax - -``` -HTTP/1.1 202 -Content-type: application/json - -{ - "[BatchSize](#SSS-UpdateEventSourceMapping-response-BatchSize)": number, - "[BisectBatchOnFunctionError](#SSS-UpdateEventSourceMapping-response-BisectBatchOnFunctionError)": boolean, - "[DestinationConfig](#SSS-UpdateEventSourceMapping-response-DestinationConfig)": { - "[OnFailure](API_DestinationConfig.md#SSS-Type-DestinationConfig-OnFailure)": { - "[Destination](API_OnFailure.md#SSS-Type-OnFailure-Destination)": "string" - }, - "[OnSuccess](API_DestinationConfig.md#SSS-Type-DestinationConfig-OnSuccess)": { - "[Destination](API_OnSuccess.md#SSS-Type-OnSuccess-Destination)": "string" - } - }, - "[EventSourceArn](#SSS-UpdateEventSourceMapping-response-EventSourceArn)": "string", - "[FunctionArn](#SSS-UpdateEventSourceMapping-response-FunctionArn)": "string", - "[LastModified](#SSS-UpdateEventSourceMapping-response-LastModified)": number, - "[LastProcessingResult](#SSS-UpdateEventSourceMapping-response-LastProcessingResult)": "string", - "[MaximumBatchingWindowInSeconds](#SSS-UpdateEventSourceMapping-response-MaximumBatchingWindowInSeconds)": number, - "[MaximumRecordAgeInSeconds](#SSS-UpdateEventSourceMapping-response-MaximumRecordAgeInSeconds)": number, - "[MaximumRetryAttempts](#SSS-UpdateEventSourceMapping-response-MaximumRetryAttempts)": number, - "[ParallelizationFactor](#SSS-UpdateEventSourceMapping-response-ParallelizationFactor)": number, - "[State](#SSS-UpdateEventSourceMapping-response-State)": "string", - "[StateTransitionReason](#SSS-UpdateEventSourceMapping-response-StateTransitionReason)": "string", - "[UUID](#SSS-UpdateEventSourceMapping-response-UUID)": "string" -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 202 response\. - -The following data is returned in JSON format by the service\. - - ** [BatchSize](#API_UpdateEventSourceMapping_ResponseSyntax) ** -The maximum number of items to retrieve in a single batch\. -Type: Integer -Valid Range: Minimum value of 1\. Maximum value of 10000\. - - ** [BisectBatchOnFunctionError](#API_UpdateEventSourceMapping_ResponseSyntax) ** -\(Streams\) If the function returns an error, split the batch in two and retry\. -Type: Boolean - - ** [DestinationConfig](#API_UpdateEventSourceMapping_ResponseSyntax) ** -\(Streams\) An Amazon SQS queue or Amazon SNS topic destination for discarded records\. -Type: [DestinationConfig](API_DestinationConfig.md) object - - ** [EventSourceArn](#API_UpdateEventSourceMapping_ResponseSyntax) ** -The Amazon Resource Name \(ARN\) of the event source\. -Type: String -Pattern: `arn:(aws[a-zA-Z0-9-]*):([a-zA-Z0-9\-])+:([a-z]{2}(-gov)?-[a-z]+-\d{1})?:(\d{12})?:(.*)` - - ** [FunctionArn](#API_UpdateEventSourceMapping_ResponseSyntax) ** -The ARN of the Lambda function\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}(-gov)?-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [LastModified](#API_UpdateEventSourceMapping_ResponseSyntax) ** -The date that the event source mapping was last updated, or its state changed, in Unix time seconds\. -Type: Timestamp - - ** [LastProcessingResult](#API_UpdateEventSourceMapping_ResponseSyntax) ** -The result of the last AWS Lambda invocation of your Lambda function\. -Type: String - - ** [MaximumBatchingWindowInSeconds](#API_UpdateEventSourceMapping_ResponseSyntax) ** -\(Streams\) The maximum amount of time to gather records before invoking the function, in seconds\. -Type: Integer -Valid Range: Minimum value of 0\. Maximum value of 300\. - - ** [MaximumRecordAgeInSeconds](#API_UpdateEventSourceMapping_ResponseSyntax) ** -\(Streams\) The maximum age of a record that Lambda sends to a function for processing\. -Type: Integer -Valid Range: Minimum value of 60\. Maximum value of 604800\. - - ** [MaximumRetryAttempts](#API_UpdateEventSourceMapping_ResponseSyntax) ** -\(Streams\) The maximum number of times to retry when the function returns an error\. -Type: Integer -Valid Range: Minimum value of 0\. Maximum value of 10000\. - - ** [ParallelizationFactor](#API_UpdateEventSourceMapping_ResponseSyntax) ** -\(Streams\) The number of batches to process from each shard concurrently\. -Type: Integer -Valid Range: Minimum value of 1\. Maximum value of 10\. - - ** [State](#API_UpdateEventSourceMapping_ResponseSyntax) ** -The state of the event source mapping\. It can be one of the following: `Creating`, `Enabling`, `Enabled`, `Disabling`, `Disabled`, `Updating`, or `Deleting`\. -Type: String - - ** [StateTransitionReason](#API_UpdateEventSourceMapping_ResponseSyntax) ** -Indicates whether the last change to the event source mapping was made by a user, or by the Lambda service\. -Type: String - - ** [UUID](#API_UpdateEventSourceMapping_ResponseSyntax) ** -The identifier of the event source mapping\. -Type: String - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceConflictException** -The resource already exists, or another operation is in progress\. -HTTP Status Code: 409 - - **ResourceInUseException** -The operation conflicts with the resource's availability\. For example, you attempted to update an EventSource Mapping in CREATING, or tried to delete a EventSource mapping currently in the UPDATING state\. -HTTP Status Code: 400 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/UpdateEventSourceMapping) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/UpdateEventSourceMapping) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/UpdateEventSourceMapping) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/UpdateEventSourceMapping) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/UpdateEventSourceMapping) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/UpdateEventSourceMapping) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/UpdateEventSourceMapping) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/UpdateEventSourceMapping) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/UpdateEventSourceMapping) \ No newline at end of file diff --git a/doc_source/API_UpdateFunctionCode.md b/doc_source/API_UpdateFunctionCode.md deleted file mode 100644 index 68fad8e8..00000000 --- a/doc_source/API_UpdateFunctionCode.md +++ /dev/null @@ -1,308 +0,0 @@ -# UpdateFunctionCode - -Updates a Lambda function's code\. - -The function's code is locked when you publish a version\. You can't modify the code of a published version, only the unpublished version\. - -## Request Syntax - -``` -PUT /2015-03-31/functions/FunctionName/code HTTP/1.1 -Content-type: application/json - -{ - "[DryRun](#SSS-UpdateFunctionCode-request-DryRun)": boolean, - "[Publish](#SSS-UpdateFunctionCode-request-Publish)": boolean, - "[RevisionId](#SSS-UpdateFunctionCode-request-RevisionId)": "string", - "[S3Bucket](#SSS-UpdateFunctionCode-request-S3Bucket)": "string", - "[S3Key](#SSS-UpdateFunctionCode-request-S3Key)": "string", - "[S3ObjectVersion](#SSS-UpdateFunctionCode-request-S3ObjectVersion)": "string", - "[ZipFile](#SSS-UpdateFunctionCode-request-ZipFile)": blob -} -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [FunctionName](#API_UpdateFunctionCode_RequestSyntax) ** -The name of the Lambda function\. - -**Name formats** -+ **Function name** \- `my-function`\. -+ **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:my-function`\. -+ **Partial ARN** \- `123456789012:function:my-function`\. -The length constraint applies only to the full ARN\. If you specify only the function name, it is limited to 64 characters in length\. -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - -## Request Body - -The request accepts the following data in JSON format\. - - ** [DryRun](#API_UpdateFunctionCode_RequestSyntax) ** -Set to true to validate the request parameters and access permissions without modifying the function code\. -Type: Boolean -Required: No - - ** [Publish](#API_UpdateFunctionCode_RequestSyntax) ** -Set to true to publish a new version of the function after updating the code\. This has the same effect as calling [PublishVersion](API_PublishVersion.md) separately\. -Type: Boolean -Required: No - - ** [RevisionId](#API_UpdateFunctionCode_RequestSyntax) ** -Only update the function if the revision ID matches the ID that's specified\. Use this option to avoid modifying a function that has changed since you last read it\. -Type: String -Required: No - - ** [S3Bucket](#API_UpdateFunctionCode_RequestSyntax) ** -An Amazon S3 bucket in the same AWS Region as your function\. The bucket can be in a different AWS account\. -Type: String -Length Constraints: Minimum length of 3\. Maximum length of 63\. -Pattern: `^[0-9A-Za-z\.\-_]*(? -The Amazon S3 key of the deployment package\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 1024\. -Required: No - - ** [S3ObjectVersion](#API_UpdateFunctionCode_RequestSyntax) ** -For versioned objects, the version of the deployment package object to use\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 1024\. -Required: No - - ** [ZipFile](#API_UpdateFunctionCode_RequestSyntax) ** -The base64\-encoded contents of the deployment package\. AWS SDK and AWS CLI clients handle the encoding for you\. -Type: Base64\-encoded binary data object -Required: No - -## Response Syntax - -``` -HTTP/1.1 200 -Content-type: application/json - -{ - "[CodeSha256](#SSS-UpdateFunctionCode-response-CodeSha256)": "string", - "[CodeSize](#SSS-UpdateFunctionCode-response-CodeSize)": number, - "[DeadLetterConfig](#SSS-UpdateFunctionCode-response-DeadLetterConfig)": { - "[TargetArn](API_DeadLetterConfig.md#SSS-Type-DeadLetterConfig-TargetArn)": "string" - }, - "[Description](#SSS-UpdateFunctionCode-response-Description)": "string", - "[Environment](#SSS-UpdateFunctionCode-response-Environment)": { - "[Error](API_EnvironmentResponse.md#SSS-Type-EnvironmentResponse-Error)": { - "[ErrorCode](API_EnvironmentError.md#SSS-Type-EnvironmentError-ErrorCode)": "string", - "[Message](API_EnvironmentError.md#SSS-Type-EnvironmentError-Message)": "string" - }, - "[Variables](API_EnvironmentResponse.md#SSS-Type-EnvironmentResponse-Variables)": { - "string" : "string" - } - }, - "[FunctionArn](#SSS-UpdateFunctionCode-response-FunctionArn)": "string", - "[FunctionName](#SSS-UpdateFunctionCode-response-FunctionName)": "string", - "[Handler](#SSS-UpdateFunctionCode-response-Handler)": "string", - "[KMSKeyArn](#SSS-UpdateFunctionCode-response-KMSKeyArn)": "string", - "[LastModified](#SSS-UpdateFunctionCode-response-LastModified)": "string", - "[LastUpdateStatus](#SSS-UpdateFunctionCode-response-LastUpdateStatus)": "string", - "[LastUpdateStatusReason](#SSS-UpdateFunctionCode-response-LastUpdateStatusReason)": "string", - "[LastUpdateStatusReasonCode](#SSS-UpdateFunctionCode-response-LastUpdateStatusReasonCode)": "string", - "[Layers](#SSS-UpdateFunctionCode-response-Layers)": [ - { - "[Arn](API_Layer.md#SSS-Type-Layer-Arn)": "string", - "[CodeSize](API_Layer.md#SSS-Type-Layer-CodeSize)": number - } - ], - "[MasterArn](#SSS-UpdateFunctionCode-response-MasterArn)": "string", - "[MemorySize](#SSS-UpdateFunctionCode-response-MemorySize)": number, - "[RevisionId](#SSS-UpdateFunctionCode-response-RevisionId)": "string", - "[Role](#SSS-UpdateFunctionCode-response-Role)": "string", - "[Runtime](#SSS-UpdateFunctionCode-response-Runtime)": "string", - "[State](#SSS-UpdateFunctionCode-response-State)": "string", - "[StateReason](#SSS-UpdateFunctionCode-response-StateReason)": "string", - "[StateReasonCode](#SSS-UpdateFunctionCode-response-StateReasonCode)": "string", - "[Timeout](#SSS-UpdateFunctionCode-response-Timeout)": number, - "[TracingConfig](#SSS-UpdateFunctionCode-response-TracingConfig)": { - "[Mode](API_TracingConfigResponse.md#SSS-Type-TracingConfigResponse-Mode)": "string" - }, - "[Version](#SSS-UpdateFunctionCode-response-Version)": "string", - "[VpcConfig](#SSS-UpdateFunctionCode-response-VpcConfig)": { - "[SecurityGroupIds](API_VpcConfigResponse.md#SSS-Type-VpcConfigResponse-SecurityGroupIds)": [ "string" ], - "[SubnetIds](API_VpcConfigResponse.md#SSS-Type-VpcConfigResponse-SubnetIds)": [ "string" ], - "[VpcId](API_VpcConfigResponse.md#SSS-Type-VpcConfigResponse-VpcId)": "string" - } -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 200 response\. - -The following data is returned in JSON format by the service\. - - ** [CodeSha256](#API_UpdateFunctionCode_ResponseSyntax) ** -The SHA256 hash of the function's deployment package\. -Type: String - - ** [CodeSize](#API_UpdateFunctionCode_ResponseSyntax) ** -The size of the function's deployment package, in bytes\. -Type: Long - - ** [DeadLetterConfig](#API_UpdateFunctionCode_ResponseSyntax) ** -The function's dead letter queue\. -Type: [DeadLetterConfig](API_DeadLetterConfig.md) object - - ** [Description](#API_UpdateFunctionCode_ResponseSyntax) ** -The function's description\. -Type: String -Length Constraints: Minimum length of 0\. Maximum length of 256\. - - ** [Environment](#API_UpdateFunctionCode_ResponseSyntax) ** -The function's environment variables\. -Type: [EnvironmentResponse](API_EnvironmentResponse.md) object - - ** [FunctionArn](#API_UpdateFunctionCode_ResponseSyntax) ** -The function's Amazon Resource Name \(ARN\)\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}(-gov)?-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_\.]+(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [FunctionName](#API_UpdateFunctionCode_ResponseSyntax) ** -The name of the function\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 170\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_\.]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [Handler](#API_UpdateFunctionCode_ResponseSyntax) ** -The function that Lambda calls to begin executing your function\. -Type: String -Length Constraints: Maximum length of 128\. -Pattern: `[^\s]+` - - ** [KMSKeyArn](#API_UpdateFunctionCode_ResponseSyntax) ** -The KMS key that's used to encrypt the function's environment variables\. This key is only returned if you've configured a customer managed CMK\. -Type: String -Pattern: `(arn:(aws[a-zA-Z-]*)?:[a-z0-9-.]+:.*)|()` - - ** [LastModified](#API_UpdateFunctionCode_ResponseSyntax) ** -The date and time that the function was last updated, in [ISO\-8601 format](https://www.w3.org/TR/NOTE-datetime) \(YYYY\-MM\-DDThh:mm:ss\.sTZD\)\. -Type: String - - ** [LastUpdateStatus](#API_UpdateFunctionCode_ResponseSyntax) ** -The status of the last update that was performed on the function\. This is first set to `Successful` after function creation completes\. -Type: String -Valid Values:` Successful | Failed | InProgress` - - ** [LastUpdateStatusReason](#API_UpdateFunctionCode_ResponseSyntax) ** -The reason for the last update that was performed on the function\. -Type: String - - ** [LastUpdateStatusReasonCode](#API_UpdateFunctionCode_ResponseSyntax) ** -The reason code for the last update that was performed on the function\. -Type: String -Valid Values:` EniLimitExceeded | InsufficientRolePermissions | InvalidConfiguration | InternalError | SubnetOutOfIPAddresses | InvalidSubnet | InvalidSecurityGroup` - - ** [Layers](#API_UpdateFunctionCode_ResponseSyntax) ** -The function's [ layers](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)\. -Type: Array of [Layer](API_Layer.md) objects - - ** [MasterArn](#API_UpdateFunctionCode_ResponseSyntax) ** -For Lambda@Edge functions, the ARN of the master function\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}(-gov)?-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [MemorySize](#API_UpdateFunctionCode_ResponseSyntax) ** -The memory that's allocated to the function\. -Type: Integer -Valid Range: Minimum value of 128\. Maximum value of 3008\. - - ** [RevisionId](#API_UpdateFunctionCode_ResponseSyntax) ** -The latest updated revision of the function or alias\. -Type: String - - ** [Role](#API_UpdateFunctionCode_ResponseSyntax) ** -The function's execution role\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:iam::\d{12}:role/?[a-zA-Z_0-9+=,.@\-_/]+` - - ** [Runtime](#API_UpdateFunctionCode_ResponseSyntax) ** -The runtime environment for the Lambda function\. -Type: String -Valid Values:` nodejs10.x | nodejs12.x | java8 | java11 | python2.7 | python3.6 | python3.7 | python3.8 | dotnetcore2.1 | go1.x | ruby2.5 | ruby2.7 | provided` - - ** [State](#API_UpdateFunctionCode_ResponseSyntax) ** -The current state of the function\. When the state is `Inactive`, you can reactivate the function by invoking it\. -Type: String -Valid Values:` Pending | Active | Inactive | Failed` - - ** [StateReason](#API_UpdateFunctionCode_ResponseSyntax) ** -The reason for the function's current state\. -Type: String - - ** [StateReasonCode](#API_UpdateFunctionCode_ResponseSyntax) ** -The reason code for the function's current state\. When the code is `Creating`, you can't invoke or modify the function\. -Type: String -Valid Values:` Idle | Creating | Restoring | EniLimitExceeded | InsufficientRolePermissions | InvalidConfiguration | InternalError | SubnetOutOfIPAddresses | InvalidSubnet | InvalidSecurityGroup` - - ** [Timeout](#API_UpdateFunctionCode_ResponseSyntax) ** -The amount of time that Lambda allows a function to run before stopping it\. -Type: Integer -Valid Range: Minimum value of 1\. - - ** [TracingConfig](#API_UpdateFunctionCode_ResponseSyntax) ** -The function's AWS X\-Ray tracing configuration\. -Type: [TracingConfigResponse](API_TracingConfigResponse.md) object - - ** [Version](#API_UpdateFunctionCode_ResponseSyntax) ** -The version of the Lambda function\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 1024\. -Pattern: `(\$LATEST|[0-9]+)` - - ** [VpcConfig](#API_UpdateFunctionCode_ResponseSyntax) ** -The function's networking configuration\. -Type: [VpcConfigResponse](API_VpcConfigResponse.md) object - -## Errors - - **CodeStorageExceededException** -You have exceeded your maximum total code size per account\. [Learn more](https://docs.aws.amazon.com/lambda/latest/dg/limits.html) -HTTP Status Code: 400 - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **PreconditionFailedException** -The RevisionId provided does not match the latest RevisionId for the Lambda function or alias\. Call the `GetFunction` or the `GetAlias` API to retrieve the latest RevisionId for your resource\. -HTTP Status Code: 412 - - **ResourceConflictException** -The resource already exists, or another operation is in progress\. -HTTP Status Code: 409 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/UpdateFunctionCode) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/UpdateFunctionCode) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/UpdateFunctionCode) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/UpdateFunctionCode) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/UpdateFunctionCode) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/UpdateFunctionCode) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/UpdateFunctionCode) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/UpdateFunctionCode) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/UpdateFunctionCode) \ No newline at end of file diff --git a/doc_source/API_UpdateFunctionConfiguration.md b/doc_source/API_UpdateFunctionConfiguration.md deleted file mode 100644 index cd1526b2..00000000 --- a/doc_source/API_UpdateFunctionConfiguration.md +++ /dev/null @@ -1,361 +0,0 @@ -# UpdateFunctionConfiguration - -Modify the version\-specific settings of a Lambda function\. - -When you update a function, Lambda provisions an instance of the function and its supporting resources\. If your function connects to a VPC, this process can take a minute\. During this time, you can't modify the function, but you can still invoke it\. The `LastUpdateStatus`, `LastUpdateStatusReason`, and `LastUpdateStatusReasonCode` fields in the response from [GetFunctionConfiguration](API_GetFunctionConfiguration.md) indicate when the update is complete and the function is processing events with the new configuration\. For more information, see [Function States](https://docs.aws.amazon.com/lambda/latest/dg/functions-states.html)\. - -These settings can vary between versions of a function and are locked when you publish a version\. You can't modify the configuration of a published version, only the unpublished version\. - -To configure function concurrency, use [PutFunctionConcurrency](API_PutFunctionConcurrency.md)\. To grant invoke permissions to an account or AWS service, use [AddPermission](API_AddPermission.md)\. - -## Request Syntax - -``` -PUT /2015-03-31/functions/FunctionName/configuration HTTP/1.1 -Content-type: application/json - -{ - "[DeadLetterConfig](#SSS-UpdateFunctionConfiguration-request-DeadLetterConfig)": { - "[TargetArn](API_DeadLetterConfig.md#SSS-Type-DeadLetterConfig-TargetArn)": "string" - }, - "[Description](#SSS-UpdateFunctionConfiguration-request-Description)": "string", - "[Environment](#SSS-UpdateFunctionConfiguration-request-Environment)": { - "[Variables](API_Environment.md#SSS-Type-Environment-Variables)": { - "string" : "string" - } - }, - "[Handler](#SSS-UpdateFunctionConfiguration-request-Handler)": "string", - "[KMSKeyArn](#SSS-UpdateFunctionConfiguration-request-KMSKeyArn)": "string", - "[Layers](#SSS-UpdateFunctionConfiguration-request-Layers)": [ "string" ], - "[MemorySize](#SSS-UpdateFunctionConfiguration-request-MemorySize)": number, - "[RevisionId](#SSS-UpdateFunctionConfiguration-request-RevisionId)": "string", - "[Role](#SSS-UpdateFunctionConfiguration-request-Role)": "string", - "[Runtime](#SSS-UpdateFunctionConfiguration-request-Runtime)": "string", - "[Timeout](#SSS-UpdateFunctionConfiguration-request-Timeout)": number, - "[TracingConfig](#SSS-UpdateFunctionConfiguration-request-TracingConfig)": { - "[Mode](API_TracingConfig.md#SSS-Type-TracingConfig-Mode)": "string" - }, - "[VpcConfig](#SSS-UpdateFunctionConfiguration-request-VpcConfig)": { - "[SecurityGroupIds](API_VpcConfig.md#SSS-Type-VpcConfig-SecurityGroupIds)": [ "string" ], - "[SubnetIds](API_VpcConfig.md#SSS-Type-VpcConfig-SubnetIds)": [ "string" ] - } -} -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [FunctionName](#API_UpdateFunctionConfiguration_RequestSyntax) ** -The name of the Lambda function\. - -**Name formats** -+ **Function name** \- `my-function`\. -+ **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:my-function`\. -+ **Partial ARN** \- `123456789012:function:my-function`\. -The length constraint applies only to the full ARN\. If you specify only the function name, it is limited to 64 characters in length\. -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - -## Request Body - -The request accepts the following data in JSON format\. - - ** [DeadLetterConfig](#API_UpdateFunctionConfiguration_RequestSyntax) ** -A dead letter queue configuration that specifies the queue or topic where Lambda sends asynchronous events when they fail processing\. For more information, see [Dead Letter Queues](https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html#dlq)\. -Type: [DeadLetterConfig](API_DeadLetterConfig.md) object -Required: No - - ** [Description](#API_UpdateFunctionConfiguration_RequestSyntax) ** -A description of the function\. -Type: String -Length Constraints: Minimum length of 0\. Maximum length of 256\. -Required: No - - ** [Environment](#API_UpdateFunctionConfiguration_RequestSyntax) ** -Environment variables that are accessible from function code during execution\. -Type: [Environment](API_Environment.md) object -Required: No - - ** [Handler](#API_UpdateFunctionConfiguration_RequestSyntax) ** -The name of the method within your code that Lambda calls to execute your function\. The format includes the file name\. It can also include namespaces and other qualifiers, depending on the runtime\. For more information, see [Programming Model](https://docs.aws.amazon.com/lambda/latest/dg/programming-model-v2.html)\. -Type: String -Length Constraints: Maximum length of 128\. -Pattern: `[^\s]+` -Required: No - - ** [KMSKeyArn](#API_UpdateFunctionConfiguration_RequestSyntax) ** -The ARN of the AWS Key Management Service \(AWS KMS\) key that's used to encrypt your function's environment variables\. If it's not provided, AWS Lambda uses a default service key\. -Type: String -Pattern: `(arn:(aws[a-zA-Z-]*)?:[a-z0-9-.]+:.*)|()` -Required: No - - ** [Layers](#API_UpdateFunctionConfiguration_RequestSyntax) ** -A list of [function layers](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) to add to the function's execution environment\. Specify each layer by its ARN, including the version\. -Type: Array of strings -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `arn:[a-zA-Z0-9-]+:lambda:[a-zA-Z0-9-]+:\d{12}:layer:[a-zA-Z0-9-_]+:[0-9]+` -Required: No - - ** [MemorySize](#API_UpdateFunctionConfiguration_RequestSyntax) ** -The amount of memory that your function has access to\. Increasing the function's memory also increases its CPU allocation\. The default value is 128 MB\. The value must be a multiple of 64 MB\. -Type: Integer -Valid Range: Minimum value of 128\. Maximum value of 3008\. -Required: No - - ** [RevisionId](#API_UpdateFunctionConfiguration_RequestSyntax) ** -Only update the function if the revision ID matches the ID that's specified\. Use this option to avoid modifying a function that has changed since you last read it\. -Type: String -Required: No - - ** [Role](#API_UpdateFunctionConfiguration_RequestSyntax) ** -The Amazon Resource Name \(ARN\) of the function's execution role\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:iam::\d{12}:role/?[a-zA-Z_0-9+=,.@\-_/]+` -Required: No - - ** [Runtime](#API_UpdateFunctionConfiguration_RequestSyntax) ** -The identifier of the function's [runtime](https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html)\. -Type: String -Valid Values:` nodejs10.x | nodejs12.x | java8 | java11 | python2.7 | python3.6 | python3.7 | python3.8 | dotnetcore2.1 | go1.x | ruby2.5 | ruby2.7 | provided` -Required: No - - ** [Timeout](#API_UpdateFunctionConfiguration_RequestSyntax) ** -The amount of time that Lambda allows a function to run before stopping it\. The default is 3 seconds\. The maximum allowed value is 900 seconds\. -Type: Integer -Valid Range: Minimum value of 1\. -Required: No - - ** [TracingConfig](#API_UpdateFunctionConfiguration_RequestSyntax) ** -Set `Mode` to `Active` to sample and trace a subset of incoming requests with AWS X\-Ray\. -Type: [TracingConfig](API_TracingConfig.md) object -Required: No - - ** [VpcConfig](#API_UpdateFunctionConfiguration_RequestSyntax) ** -For network connectivity to AWS resources in a VPC, specify a list of security groups and subnets in the VPC\. When you connect a function to a VPC, it can only access resources and the internet through that VPC\. For more information, see [VPC Settings](https://docs.aws.amazon.com/lambda/latest/dg/configuration-vpc.html)\. -Type: [VpcConfig](API_VpcConfig.md) object -Required: No - -## Response Syntax - -``` -HTTP/1.1 200 -Content-type: application/json - -{ - "[CodeSha256](#SSS-UpdateFunctionConfiguration-response-CodeSha256)": "string", - "[CodeSize](#SSS-UpdateFunctionConfiguration-response-CodeSize)": number, - "[DeadLetterConfig](#SSS-UpdateFunctionConfiguration-response-DeadLetterConfig)": { - "[TargetArn](API_DeadLetterConfig.md#SSS-Type-DeadLetterConfig-TargetArn)": "string" - }, - "[Description](#SSS-UpdateFunctionConfiguration-response-Description)": "string", - "[Environment](#SSS-UpdateFunctionConfiguration-response-Environment)": { - "[Error](API_EnvironmentResponse.md#SSS-Type-EnvironmentResponse-Error)": { - "[ErrorCode](API_EnvironmentError.md#SSS-Type-EnvironmentError-ErrorCode)": "string", - "[Message](API_EnvironmentError.md#SSS-Type-EnvironmentError-Message)": "string" - }, - "[Variables](API_EnvironmentResponse.md#SSS-Type-EnvironmentResponse-Variables)": { - "string" : "string" - } - }, - "[FunctionArn](#SSS-UpdateFunctionConfiguration-response-FunctionArn)": "string", - "[FunctionName](#SSS-UpdateFunctionConfiguration-response-FunctionName)": "string", - "[Handler](#SSS-UpdateFunctionConfiguration-response-Handler)": "string", - "[KMSKeyArn](#SSS-UpdateFunctionConfiguration-response-KMSKeyArn)": "string", - "[LastModified](#SSS-UpdateFunctionConfiguration-response-LastModified)": "string", - "[LastUpdateStatus](#SSS-UpdateFunctionConfiguration-response-LastUpdateStatus)": "string", - "[LastUpdateStatusReason](#SSS-UpdateFunctionConfiguration-response-LastUpdateStatusReason)": "string", - "[LastUpdateStatusReasonCode](#SSS-UpdateFunctionConfiguration-response-LastUpdateStatusReasonCode)": "string", - "[Layers](#SSS-UpdateFunctionConfiguration-response-Layers)": [ - { - "[Arn](API_Layer.md#SSS-Type-Layer-Arn)": "string", - "[CodeSize](API_Layer.md#SSS-Type-Layer-CodeSize)": number - } - ], - "[MasterArn](#SSS-UpdateFunctionConfiguration-response-MasterArn)": "string", - "[MemorySize](#SSS-UpdateFunctionConfiguration-response-MemorySize)": number, - "[RevisionId](#SSS-UpdateFunctionConfiguration-response-RevisionId)": "string", - "[Role](#SSS-UpdateFunctionConfiguration-response-Role)": "string", - "[Runtime](#SSS-UpdateFunctionConfiguration-response-Runtime)": "string", - "[State](#SSS-UpdateFunctionConfiguration-response-State)": "string", - "[StateReason](#SSS-UpdateFunctionConfiguration-response-StateReason)": "string", - "[StateReasonCode](#SSS-UpdateFunctionConfiguration-response-StateReasonCode)": "string", - "[Timeout](#SSS-UpdateFunctionConfiguration-response-Timeout)": number, - "[TracingConfig](#SSS-UpdateFunctionConfiguration-response-TracingConfig)": { - "[Mode](API_TracingConfigResponse.md#SSS-Type-TracingConfigResponse-Mode)": "string" - }, - "[Version](#SSS-UpdateFunctionConfiguration-response-Version)": "string", - "[VpcConfig](#SSS-UpdateFunctionConfiguration-response-VpcConfig)": { - "[SecurityGroupIds](API_VpcConfigResponse.md#SSS-Type-VpcConfigResponse-SecurityGroupIds)": [ "string" ], - "[SubnetIds](API_VpcConfigResponse.md#SSS-Type-VpcConfigResponse-SubnetIds)": [ "string" ], - "[VpcId](API_VpcConfigResponse.md#SSS-Type-VpcConfigResponse-VpcId)": "string" - } -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 200 response\. - -The following data is returned in JSON format by the service\. - - ** [CodeSha256](#API_UpdateFunctionConfiguration_ResponseSyntax) ** -The SHA256 hash of the function's deployment package\. -Type: String - - ** [CodeSize](#API_UpdateFunctionConfiguration_ResponseSyntax) ** -The size of the function's deployment package, in bytes\. -Type: Long - - ** [DeadLetterConfig](#API_UpdateFunctionConfiguration_ResponseSyntax) ** -The function's dead letter queue\. -Type: [DeadLetterConfig](API_DeadLetterConfig.md) object - - ** [Description](#API_UpdateFunctionConfiguration_ResponseSyntax) ** -The function's description\. -Type: String -Length Constraints: Minimum length of 0\. Maximum length of 256\. - - ** [Environment](#API_UpdateFunctionConfiguration_ResponseSyntax) ** -The function's environment variables\. -Type: [EnvironmentResponse](API_EnvironmentResponse.md) object - - ** [FunctionArn](#API_UpdateFunctionConfiguration_ResponseSyntax) ** -The function's Amazon Resource Name \(ARN\)\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}(-gov)?-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_\.]+(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [FunctionName](#API_UpdateFunctionConfiguration_ResponseSyntax) ** -The name of the function\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 170\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_\.]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [Handler](#API_UpdateFunctionConfiguration_ResponseSyntax) ** -The function that Lambda calls to begin executing your function\. -Type: String -Length Constraints: Maximum length of 128\. -Pattern: `[^\s]+` - - ** [KMSKeyArn](#API_UpdateFunctionConfiguration_ResponseSyntax) ** -The KMS key that's used to encrypt the function's environment variables\. This key is only returned if you've configured a customer managed CMK\. -Type: String -Pattern: `(arn:(aws[a-zA-Z-]*)?:[a-z0-9-.]+:.*)|()` - - ** [LastModified](#API_UpdateFunctionConfiguration_ResponseSyntax) ** -The date and time that the function was last updated, in [ISO\-8601 format](https://www.w3.org/TR/NOTE-datetime) \(YYYY\-MM\-DDThh:mm:ss\.sTZD\)\. -Type: String - - ** [LastUpdateStatus](#API_UpdateFunctionConfiguration_ResponseSyntax) ** -The status of the last update that was performed on the function\. This is first set to `Successful` after function creation completes\. -Type: String -Valid Values:` Successful | Failed | InProgress` - - ** [LastUpdateStatusReason](#API_UpdateFunctionConfiguration_ResponseSyntax) ** -The reason for the last update that was performed on the function\. -Type: String - - ** [LastUpdateStatusReasonCode](#API_UpdateFunctionConfiguration_ResponseSyntax) ** -The reason code for the last update that was performed on the function\. -Type: String -Valid Values:` EniLimitExceeded | InsufficientRolePermissions | InvalidConfiguration | InternalError | SubnetOutOfIPAddresses | InvalidSubnet | InvalidSecurityGroup` - - ** [Layers](#API_UpdateFunctionConfiguration_ResponseSyntax) ** -The function's [ layers](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)\. -Type: Array of [Layer](API_Layer.md) objects - - ** [MasterArn](#API_UpdateFunctionConfiguration_ResponseSyntax) ** -For Lambda@Edge functions, the ARN of the master function\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}(-gov)?-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [MemorySize](#API_UpdateFunctionConfiguration_ResponseSyntax) ** -The memory that's allocated to the function\. -Type: Integer -Valid Range: Minimum value of 128\. Maximum value of 3008\. - - ** [RevisionId](#API_UpdateFunctionConfiguration_ResponseSyntax) ** -The latest updated revision of the function or alias\. -Type: String - - ** [Role](#API_UpdateFunctionConfiguration_ResponseSyntax) ** -The function's execution role\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:iam::\d{12}:role/?[a-zA-Z_0-9+=,.@\-_/]+` - - ** [Runtime](#API_UpdateFunctionConfiguration_ResponseSyntax) ** -The runtime environment for the Lambda function\. -Type: String -Valid Values:` nodejs10.x | nodejs12.x | java8 | java11 | python2.7 | python3.6 | python3.7 | python3.8 | dotnetcore2.1 | go1.x | ruby2.5 | ruby2.7 | provided` - - ** [State](#API_UpdateFunctionConfiguration_ResponseSyntax) ** -The current state of the function\. When the state is `Inactive`, you can reactivate the function by invoking it\. -Type: String -Valid Values:` Pending | Active | Inactive | Failed` - - ** [StateReason](#API_UpdateFunctionConfiguration_ResponseSyntax) ** -The reason for the function's current state\. -Type: String - - ** [StateReasonCode](#API_UpdateFunctionConfiguration_ResponseSyntax) ** -The reason code for the function's current state\. When the code is `Creating`, you can't invoke or modify the function\. -Type: String -Valid Values:` Idle | Creating | Restoring | EniLimitExceeded | InsufficientRolePermissions | InvalidConfiguration | InternalError | SubnetOutOfIPAddresses | InvalidSubnet | InvalidSecurityGroup` - - ** [Timeout](#API_UpdateFunctionConfiguration_ResponseSyntax) ** -The amount of time that Lambda allows a function to run before stopping it\. -Type: Integer -Valid Range: Minimum value of 1\. - - ** [TracingConfig](#API_UpdateFunctionConfiguration_ResponseSyntax) ** -The function's AWS X\-Ray tracing configuration\. -Type: [TracingConfigResponse](API_TracingConfigResponse.md) object - - ** [Version](#API_UpdateFunctionConfiguration_ResponseSyntax) ** -The version of the Lambda function\. -Type: String -Length Constraints: Minimum length of 1\. Maximum length of 1024\. -Pattern: `(\$LATEST|[0-9]+)` - - ** [VpcConfig](#API_UpdateFunctionConfiguration_ResponseSyntax) ** -The function's networking configuration\. -Type: [VpcConfigResponse](API_VpcConfigResponse.md) object - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **PreconditionFailedException** -The RevisionId provided does not match the latest RevisionId for the Lambda function or alias\. Call the `GetFunction` or the `GetAlias` API to retrieve the latest RevisionId for your resource\. -HTTP Status Code: 412 - - **ResourceConflictException** -The resource already exists, or another operation is in progress\. -HTTP Status Code: 409 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/UpdateFunctionConfiguration) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/UpdateFunctionConfiguration) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/UpdateFunctionConfiguration) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/UpdateFunctionConfiguration) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/UpdateFunctionConfiguration) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/UpdateFunctionConfiguration) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/UpdateFunctionConfiguration) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/UpdateFunctionConfiguration) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/UpdateFunctionConfiguration) \ No newline at end of file diff --git a/doc_source/API_UpdateFunctionEventInvokeConfig.md b/doc_source/API_UpdateFunctionEventInvokeConfig.md deleted file mode 100644 index f1ce6698..00000000 --- a/doc_source/API_UpdateFunctionEventInvokeConfig.md +++ /dev/null @@ -1,160 +0,0 @@ -# UpdateFunctionEventInvokeConfig - -Updates the configuration for asynchronous invocation for a function, version, or alias\. - -To configure options for asynchronous invocation, use [PutFunctionEventInvokeConfig](API_PutFunctionEventInvokeConfig.md)\. - -## Request Syntax - -``` -POST /2019-09-25/functions/FunctionName/event-invoke-config?Qualifier=Qualifier HTTP/1.1 -Content-type: application/json - -{ - "[DestinationConfig](#SSS-UpdateFunctionEventInvokeConfig-request-DestinationConfig)": { - "[OnFailure](API_DestinationConfig.md#SSS-Type-DestinationConfig-OnFailure)": { - "[Destination](API_OnFailure.md#SSS-Type-OnFailure-Destination)": "string" - }, - "[OnSuccess](API_DestinationConfig.md#SSS-Type-DestinationConfig-OnSuccess)": { - "[Destination](API_OnSuccess.md#SSS-Type-OnSuccess-Destination)": "string" - } - }, - "[MaximumEventAgeInSeconds](#SSS-UpdateFunctionEventInvokeConfig-request-MaximumEventAgeInSeconds)": number, - "[MaximumRetryAttempts](#SSS-UpdateFunctionEventInvokeConfig-request-MaximumRetryAttempts)": number -} -``` - -## URI Request Parameters - -The request requires the following URI parameters\. - - ** [FunctionName](#API_UpdateFunctionEventInvokeConfig_RequestSyntax) ** -The name of the Lambda function, version, or alias\. - -**Name formats** -+ **Function name** \- `my-function` \(name\-only\), `my-function:v1` \(with alias\)\. -+ **Function ARN** \- `arn:aws:lambda:us-west-2:123456789012:function:my-function`\. -+ **Partial ARN** \- `123456789012:function:my-function`\. -You can append a version number or alias to any of the formats\. The length constraint applies only to the full ARN\. If you specify only the function name, it is limited to 64 characters in length\. -Length Constraints: Minimum length of 1\. Maximum length of 140\. -Pattern: `(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [Qualifier](#API_UpdateFunctionEventInvokeConfig_RequestSyntax) ** -A version number or alias name\. -Length Constraints: Minimum length of 1\. Maximum length of 128\. -Pattern: `(|[a-zA-Z0-9$_-]+)` - -## Request Body - -The request accepts the following data in JSON format\. - - ** [DestinationConfig](#API_UpdateFunctionEventInvokeConfig_RequestSyntax) ** -A destination for events after they have been sent to a function for processing\. - -**Destinations** -+ **Function** \- The Amazon Resource Name \(ARN\) of a Lambda function\. -+ **Queue** \- The ARN of an SQS queue\. -+ **Topic** \- The ARN of an SNS topic\. -+ **Event Bus** \- The ARN of an Amazon EventBridge event bus\. -Type: [DestinationConfig](API_DestinationConfig.md) object -Required: No - - ** [MaximumEventAgeInSeconds](#API_UpdateFunctionEventInvokeConfig_RequestSyntax) ** -The maximum age of a request that Lambda sends to a function for processing\. -Type: Integer -Valid Range: Minimum value of 60\. Maximum value of 21600\. -Required: No - - ** [MaximumRetryAttempts](#API_UpdateFunctionEventInvokeConfig_RequestSyntax) ** -The maximum number of times to retry when the function returns an error\. -Type: Integer -Valid Range: Minimum value of 0\. Maximum value of 2\. -Required: No - -## Response Syntax - -``` -HTTP/1.1 200 -Content-type: application/json - -{ - "[DestinationConfig](#SSS-UpdateFunctionEventInvokeConfig-response-DestinationConfig)": { - "[OnFailure](API_DestinationConfig.md#SSS-Type-DestinationConfig-OnFailure)": { - "[Destination](API_OnFailure.md#SSS-Type-OnFailure-Destination)": "string" - }, - "[OnSuccess](API_DestinationConfig.md#SSS-Type-DestinationConfig-OnSuccess)": { - "[Destination](API_OnSuccess.md#SSS-Type-OnSuccess-Destination)": "string" - } - }, - "[FunctionArn](#SSS-UpdateFunctionEventInvokeConfig-response-FunctionArn)": "string", - "[LastModified](#SSS-UpdateFunctionEventInvokeConfig-response-LastModified)": number, - "[MaximumEventAgeInSeconds](#SSS-UpdateFunctionEventInvokeConfig-response-MaximumEventAgeInSeconds)": number, - "[MaximumRetryAttempts](#SSS-UpdateFunctionEventInvokeConfig-response-MaximumRetryAttempts)": number -} -``` - -## Response Elements - -If the action is successful, the service sends back an HTTP 200 response\. - -The following data is returned in JSON format by the service\. - - ** [DestinationConfig](#API_UpdateFunctionEventInvokeConfig_ResponseSyntax) ** -A destination for events after they have been sent to a function for processing\. - -**Destinations** -+ **Function** \- The Amazon Resource Name \(ARN\) of a Lambda function\. -+ **Queue** \- The ARN of an SQS queue\. -+ **Topic** \- The ARN of an SNS topic\. -+ **Event Bus** \- The ARN of an Amazon EventBridge event bus\. -Type: [DestinationConfig](API_DestinationConfig.md) object - - ** [FunctionArn](#API_UpdateFunctionEventInvokeConfig_ResponseSyntax) ** -The Amazon Resource Name \(ARN\) of the function\. -Type: String -Pattern: `arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}(-gov)?-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?` - - ** [LastModified](#API_UpdateFunctionEventInvokeConfig_ResponseSyntax) ** -The date and time that the configuration was last updated, in Unix time seconds\. -Type: Timestamp - - ** [MaximumEventAgeInSeconds](#API_UpdateFunctionEventInvokeConfig_ResponseSyntax) ** -The maximum age of a request that Lambda sends to a function for processing\. -Type: Integer -Valid Range: Minimum value of 60\. Maximum value of 21600\. - - ** [MaximumRetryAttempts](#API_UpdateFunctionEventInvokeConfig_ResponseSyntax) ** -The maximum number of times to retry when the function returns an error\. -Type: Integer -Valid Range: Minimum value of 0\. Maximum value of 2\. - -## Errors - - **InvalidParameterValueException** -One of the parameters in the request is invalid\. -HTTP Status Code: 400 - - **ResourceNotFoundException** -The resource specified in the request does not exist\. -HTTP Status Code: 404 - - **ServiceException** -The AWS Lambda service encountered an internal error\. -HTTP Status Code: 500 - - **TooManyRequestsException** -The request throughput limit was exceeded\. -HTTP Status Code: 429 - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS Command Line Interface](https://docs.aws.amazon.com/goto/aws-cli/lambda-2015-03-31/UpdateFunctionEventInvokeConfig) -+ [AWS SDK for \.NET](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/UpdateFunctionEventInvokeConfig) -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/UpdateFunctionEventInvokeConfig) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/UpdateFunctionEventInvokeConfig) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/UpdateFunctionEventInvokeConfig) -+ [AWS SDK for JavaScript](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/lambda-2015-03-31/UpdateFunctionEventInvokeConfig) -+ [AWS SDK for PHP V3](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/UpdateFunctionEventInvokeConfig) -+ [AWS SDK for Python](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/UpdateFunctionEventInvokeConfig) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/UpdateFunctionEventInvokeConfig) \ No newline at end of file diff --git a/doc_source/API_VpcConfig.md b/doc_source/API_VpcConfig.md deleted file mode 100644 index 8b29a124..00000000 --- a/doc_source/API_VpcConfig.md +++ /dev/null @@ -1,25 +0,0 @@ -# VpcConfig - -The VPC security groups and subnets that are attached to a Lambda function\. For more information, see [VPC Settings](https://docs.aws.amazon.com/lambda/latest/dg/configuration-vpc.html)\. - -## Contents - - **SecurityGroupIds** -A list of VPC security groups IDs\. -Type: Array of strings -Array Members: Maximum number of 5 items\. -Required: No - - **SubnetIds** -A list of VPC subnet IDs\. -Type: Array of strings -Array Members: Maximum number of 16 items\. -Required: No - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/VpcConfig) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/VpcConfig) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/VpcConfig) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/VpcConfig) \ No newline at end of file diff --git a/doc_source/API_VpcConfigResponse.md b/doc_source/API_VpcConfigResponse.md deleted file mode 100644 index 37a49bed..00000000 --- a/doc_source/API_VpcConfigResponse.md +++ /dev/null @@ -1,30 +0,0 @@ -# VpcConfigResponse - -The VPC security groups and subnets that are attached to a Lambda function\. - -## Contents - - **SecurityGroupIds** -A list of VPC security groups IDs\. -Type: Array of strings -Array Members: Maximum number of 5 items\. -Required: No - - **SubnetIds** -A list of VPC subnet IDs\. -Type: Array of strings -Array Members: Maximum number of 16 items\. -Required: No - - **VpcId** -The ID of the VPC\. -Type: String -Required: No - -## See Also - -For more information about using this API in one of the language\-specific AWS SDKs, see the following: -+ [AWS SDK for C\+\+](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/VpcConfigResponse) -+ [AWS SDK for Go](https://docs.aws.amazon.com/goto/SdkForGoV1/lambda-2015-03-31/VpcConfigResponse) -+ [AWS SDK for Java](https://docs.aws.amazon.com/goto/SdkForJava/lambda-2015-03-31/VpcConfigResponse) -+ [AWS SDK for Ruby V3](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/VpcConfigResponse) \ No newline at end of file diff --git a/doc_source/access-control-identity-based.md b/doc_source/access-control-identity-based.md deleted file mode 100644 index 9894cd0e..00000000 --- a/doc_source/access-control-identity-based.md +++ /dev/null @@ -1,236 +0,0 @@ -# Identity\-based IAM policies for AWS Lambda - -You can use identity\-based policies in AWS Identity and Access Management \(IAM\) to grant users in your account access to Lambda\. Identity\-based policies can apply to users directly, or to groups and roles that are associated with a user\. You can also grant users in another account permission to assume a role in your account and access your Lambda resources\. - -Lambda provides managed policies that grant access to Lambda API actions and, in some cases, access to other services used to develop and manage Lambda resources\. Lambda updates the managed policies as needed, to ensure that your users have access to new features when they're released\. -+ **AWSLambdaFullAccess** – Grants full access to AWS Lambda actions and other services used to develop and maintain Lambda resources\. -+ **AWSLambdaReadOnlyAccess** – Grants read\-only access to AWS Lambda resources\. -+ **AWSLambdaRole** – Grants permissions to invoke Lambda functions\. - -Managed policies grant permission to API actions without restricting the functions or layers that a user can modify\. For finer\-grained control, you can create your own policies that limit the scope of a user's permissions\. - -**Topics** -+ [Function development](#permissions-user-function) -+ [Layer development and use](#permissions-user-layer) -+ [Cross\-account roles](#permissions-user-xaccount) - -## Function development - -The following shows an example of a permissions policy with limited scope\. It allows a user to create and manage Lambda functions named with a designated prefix \(`intern-`\), and configured with a designated execution role\. - -**Example Function development policy** - -``` -{ - "Version": "2012-10-17", - "Statement": [ - { - "Sid": "ReadOnlyPermissions", - "Effect": "Allow", - "Action": [ - "lambda:GetAccountSettings", - "lambda:ListFunctions", - "lambda:ListTags", - "lambda:GetEventSourceMapping", - "lambda:ListEventSourceMappings", - "iam:ListRoles" - ], - "Resource": "*" - }, - { - "Sid": "DevelopFunctions", - "Effect": "Allow", - "NotAction": [ - "lambda:AddPermission", - "lambda:PutFunctionConcurrency" - ], - "Resource": "arn:aws:lambda:*:*:function:intern-*" - }, - { - "Sid": "DevelopEventSourceMappings", - "Effect": "Allow", - "Action": [ - "lambda:DeleteEventSourceMapping", - "lambda:UpdateEventSourceMapping", - "lambda:CreateEventSourceMapping" - ], - "Resource": "*", - "Condition": { - "StringLike": { - "lambda:FunctionArn": "arn:aws:lambda:*:*:function:intern-*" - } - } - }, - { - "Sid": "PassExecutionRole", - "Effect": "Allow", - "Action": [ - "iam:ListRolePolicies", - "iam:ListAttachedRolePolicies", - "iam:GetRole", - "iam:GetRolePolicy", - "iam:PassRole", - "iam:SimulatePrincipalPolicy" - ], - "Resource": "arn:aws:iam::*:role/intern-lambda-execution-role" - }, - { - "Sid": "ViewExecutionRolePolicies", - "Effect": "Allow", - "Action": [ - "iam:GetPolicy", - "iam:GetPolicyVersion" - ], - "Resource": "arn:aws:iam::aws:policy/*" - }, - { - "Sid": "ViewLogs", - "Effect": "Allow", - "Action": [ - "logs:*" - ], - "Resource": "arn:aws:logs:*:*:log-group:/aws/lambda/intern-*" - } - ] -} -``` - -The permissions in the policy are organized into statements based on the [resources and conditions](lambda-api-permissions-ref.md) that they support\. -+ `ReadOnlyPermissions` – The Lambda console uses these permissions when you browse and view functions\. They don't support resource patterns or conditions\. - - ``` - "Action": [ - "lambda:GetAccountSettings", - "lambda:ListFunctions", - "lambda:ListTags", - "lambda:GetEventSourceMapping", - "lambda:ListEventSourceMappings", - "iam:ListRoles" - ], - "Resource": "*" - ``` -+ `DevelopFunctions` – Use any Lambda action that operates on functions prefixed with `intern-`, *except* `AddPermission` and `PutFunctionConcurrency`\. `AddPermission` modifies the [resource\-based policy](access-control-resource-based.md) on the function and can have security implications\. `PutFunctionConcurrency` reserves scaling capacity for a function and can take capacity away from other functions\. - - ``` - "NotAction": [ - "lambda:AddPermission", - "lambda:PutFunctionConcurrency" - ], - "Resource": "arn:aws:lambda:*:*:function:intern-*" - ``` -+ `DevelopEventSourceMappings` – Manage event source mappings on functions that are prefixed with `intern-`\. These actions operate on event source mappings, but you can restrict them by function with a *condition*\. - - ``` - "Action": [ - "lambda:DeleteEventSourceMapping", - "lambda:UpdateEventSourceMapping", - "lambda:CreateEventSourceMapping" - ], - "Resource": "*", - "Condition": { - "StringLike": { - "lambda:FunctionArn": "arn:aws:lambda:*:*:function:intern-*" - } - } - ``` -+ `PassExecutionRole` – View and pass only a role named `intern-lambda-execution-role`, which must be created and managed by a user with IAM permissions\. `PassRole` is used when you assign an execution role to a function\. - - ``` - "Action": [ - "iam:ListRolePolicies", - "iam:ListAttachedRolePolicies", - "iam:GetRole", - "iam:GetRolePolicy", - "iam:PassRole", - "iam:SimulatePrincipalPolicy" - ], - "Resource": "arn:aws:iam::*:role/intern-lambda-execution-role" - ``` -+ `ViewExecutionRolePolicies` – View the AWS\-provided managed policies that are attached to the execution role\. This lets you view the function's permissions in the console, but doesn't include permission to view policies that were created by other users in the account\. - - ``` - "Action": [ - "iam:GetPolicy", - "iam:GetPolicyVersion" - ], - "Resource": "arn:aws:iam::aws:policy/*" - ``` -+ `ViewLogs` – Use CloudWatch Logs to view logs for functions that are prefixed with `intern-`\. - - ``` - "Action": [ - "logs:*" - ], - "Resource": "arn:aws:logs:*:*:log-group:/aws/lambda/intern-*" - ``` - -This policy allows a user to get started with Lambda, without putting other users' resources at risk\. It doesn't allow a user to configure a function to be triggered by or call other AWS services, which requires broader IAM permissions\. It also doesn't include permission to services that don't support limited\-scope policies, like CloudWatch and X\-Ray\. Use the read\-only policies for these services to give the user access to metrics and trace data\. - -When you configure triggers for your function, you need access to use the AWS service that invokes your function\. For example, to configure an Amazon S3 trigger, you need permission to Amazon S3 actions to manage bucket notifications\. Many of these permissions are included in the **AWSLambdaFullAccess** managed policy\. Example policies are available in this guide's [GitHub repository](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/iam-policies)\. - -## Layer development and use - -The following policy grants a user permission to create layers and use them with functions\. The resource patterns allow the user to work in any AWS Region and with any layer version, as long as the name of the layer starts with `test-`\. - -**Example Layer development policy** - -``` -{ - "Version": "2012-10-17", - "Statement": [ - { - "Sid": "PublishLayers", - "Effect": "Allow", - "Action": [ - "lambda:PublishLayerVersion" - ], - "Resource": "arn:aws:lambda:*:*:layer:test-*" - }, - { - "Sid": "ManageLayerVersions", - "Effect": "Allow", - "Action": [ - "lambda:GetLayerVersion", - "lambda:DeleteLayerVersion" - ], - "Resource": "arn:aws:lambda:*:*:layer:test-*:*" - } - ] -} -``` - -You can also enforce layer use during function creation and configuration with the `lambda:Layer` condition\. For example, you can prevent users from using layers published by other accounts\. The following policy adds a condition to the `CreateFunction` and `UpdateFunctionConfiguration` actions to require that any layers specified come from account `123456789012`\. - -``` -{ - "Version": "2012-10-17", - "Statement": [ - { - "Sid": "ConfigureFunctions", - "Effect": "Allow", - "Action": [ - "lambda:CreateFunction", - "lambda:UpdateFunctionConfiguration" - ], - "Resource": "*", - "Condition": { - "ForAllValues:StringLike": { - "lambda:Layer": [ - "arn:aws:lambda:*:123456789012:layer:*:*" - ] - } - } - } - ] -} -``` - -To ensure that the condition applies, verify that no other statements grant the user permission to these actions\. - -## Cross\-account roles - -You can apply any of the preceding policies and statements to a role, which you can then share with another account to give it access to your Lambda resources\. Unlike an IAM user, a role doesn't have credentials for authentication\. Instead, it has a *trust policy* that specifies who can assume the role and use its permissions\. - -You can use cross\-account roles to give accounts that you trust access to Lambda actions and resources\. If you just want to grant permission to invoke a function or use a layer, use [resource\-based policies](access-control-resource-based.md) instead\. - -For more information, see [IAM roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) in the *IAM User Guide*\. \ No newline at end of file diff --git a/doc_source/access-control-resource-based.md b/doc_source/access-control-resource-based.md deleted file mode 100644 index 3cf8961d..00000000 --- a/doc_source/access-control-resource-based.md +++ /dev/null @@ -1,161 +0,0 @@ -# Using resource\-based policies for AWS Lambda - -AWS Lambda supports resource\-based permissions policies for Lambda functions and layers\. Resource\-based policies let you grant usage permission to other accounts on a per\-resource basis\. You also use a resource\-based policy to allow an AWS service to invoke your function\. - -For Lambda functions, you can [grant an account permission](#permissions-resource-xaccountinvoke) to invoke or manage a function\. You can add multiple statements to grant access to multiple accounts, or let any account invoke your function\. For functions that another AWS service invokes in response to activity in your account, you use the policy to [grant invoke permission to the service](#permissions-resource-serviceinvoke)\. - -**To view a function's resource\-based policy** - -1. Open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions)\. - -1. Choose a function\. - -1. Choose **Permissions**\. - -1. The resource\-based policy shows the permissions that are applied when another account or AWS service attempts to access the function\. The following example shows a statement that allows Amazon S3 to invoke a function named `my-function` for a bucket named `my-bucket` in account `123456789012`\. -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/permissions-resourcebased.png) - -For Lambda layers, you use a resource\-based policy on a version of the layer to let other accounts use it\. In addition to policies that grant permission to a single account or all accounts, for layers, you can also grant permission to all accounts in an organization\. - -**Note** -You can only update resource\-based policies for Lambda resources within the scope of the [AddPermission](API_AddPermission.md) and [AddLayerVersionPermission](API_AddLayerVersionPermission.md) API actions\. You can't author policies for your Lambda resources in JSON, or use conditions that don't map to parameters for those actions\. - -Resource\-based policies apply to a single function, version, alias, or layer version\. They grant permission to one or more services and accounts\. For trusted accounts that you want to have access to multiple resources, or to use API actions that resource\-based policies don't support, you can use [cross\-account roles](access-control-identity-based.md)\. - -**Topics** -+ [Granting function access to AWS services](#permissions-resource-serviceinvoke) -+ [Granting function access to other accounts](#permissions-resource-xaccountinvoke) -+ [Granting layer access to other accounts](#permissions-resource-xaccountlayer) -+ [Cleaning up resource\-based policies](#permissions-resource-cleanup) - -## Granting function access to AWS services - -When you [use an AWS service to invoke your function](lambda-services.md), you grant permission in a statement on a resource\-based policy\. You can apply the statement to the function, or limit it to a single version or alias\. - -**Note** -When you add a trigger to your function with the Lambda console, the console updates the function's resource\-based policy to allow the service to invoke it\. To grant permissions to other accounts or services that aren't available in the Lambda console, use the AWS CLI\. - -Add a statement with the `add-permission` command\. The simplest resource\-based policy statement allows a service to invoke a function\. The following command grants Amazon SNS permission to invoke a function named `my-function`\. - -``` -$ aws lambda add-permission --function-name my-function --action lambda:InvokeFunction --statement-id sns \ ---principal sns.amazonaws.com --output text -{"Sid":"sns","Effect":"Allow","Principal":{"Service":"sns.amazonaws.com"},"Action":"lambda:InvokeFunction","Resource":"arn:aws:lambda:us-east-2:123456789012:function:my-function"} -``` - -This lets Amazon SNS invoke the function, but it doesn't restrict the Amazon SNS topic that triggers the invocation\. To ensure that your function is only invoked by a specific resource, specify the Amazon Resource Name \(ARN\) of the resource with the `source-arn` option\. The following command only allows Amazon SNS to invoke the function for subscriptions to a topic named `my-topic`\. - -``` -$ aws lambda add-permission --function-name my-function --action lambda:InvokeFunction --statement-id sns-my-topic \ ---principal sns.amazonaws.com --source-arn arn:aws:sns:us-east-2:123456789012:my-topic -``` - -Some services can invoke functions in other accounts\. If you specify a source ARN that has your account ID in it, that isn't an issue\. For Amazon S3, however, the source is a bucket whose ARN doesn't have an account ID in it\. It's possible that you could delete the bucket and another account could create a bucket with the same name\. Use the `account-id` option to ensure that only resources in your account can invoke the function\. - -``` -$ aws lambda add-permission --function-name my-function --action lambda:InvokeFunction --statement-id s3-account \ ---principal s3.amazonaws.com --source-arn arn:aws:s3:::my-bucket-123456 --source-account 123456789012 -``` - -## Granting function access to other accounts - -To grant permissions to another AWS account, specify the account ID as the `principal`\. The following example grants account `210987654321` permission to invoke `my-function` with the `prod` alias\. - -``` -$ aws lambda add-permission --function-name my-function:prod --statement-id xaccount --action lambda:InvokeFunction \ ---principal 210987654321 --output text -{"Sid":"xaccount","Effect":"Allow","Principal":{"AWS":"arn:aws:iam::210987654321:root"},"Action":"lambda:InvokeFunction","Resource":"arn:aws:lambda:us-east-2:123456789012:function:my-function"} -``` - -The resource\-based policy grants permission for the other account to access the function, but doesn't allow users in that account to exceed their permissions\. Users in the other account must have the corresponding [user permissions](access-control-identity-based.md) to use the Lambda API\. - -To limit access to a user, group, or role in another account, specify the full ARN of the identity as the principal\. For example, `arn:aws:iam::123456789012:user/developer`\. - -The [alias](configuration-aliases.md) limits which version the other account can invoke\. It requires the other account to include the alias in the function ARN\. - -``` -$ aws lambda invoke --function-name arn:aws:lambda:us-west-2:123456789012:function:my-function:prod out -{ - "StatusCode": 200, - "ExecutedVersion": "1" -} -``` - -You can then update the alias to point to new versions as needed\. When you update the alias, the other account doesn't need to change its code to use the new version, and it only has permission to invoke the version that you choose\. - -You can grant cross\-account access for most API actions that [operate on an existing function](lambda-api-permissions-ref.md#permissions-resources-function)\. For example, you could grant access to `lambda:ListAliases` to let an account get a list of aliases, or `lambda:GetFunction` to let them download your function code\. Add each permission separately, or use `lambda:*` to grant access to all actions for the specified function\. - -**Cross\-account APIs** -+ [Invoke](API_Invoke.md) -+ [GetFunction](API_GetFunction.md) -+ [GetFunctionConfiguration](API_GetFunctionConfiguration.md) -+ [UpdateFunctionCode](API_UpdateFunctionCode.md) -+ [DeleteFunction](API_DeleteFunction.md) -+ [PublishVersion](API_PublishVersion.md) -+ [ListVersionsByFunction](API_ListVersionsByFunction.md) -+ [CreateAlias](API_CreateAlias.md) -+ [GetAlias](API_GetAlias.md) -+ [ListAliases](API_ListAliases.md) -+ [UpdateAlias](API_UpdateAlias.md) -+ [DeleteAlias](API_DeleteAlias.md) -+ [GetPolicy](API_GetPolicy.md) -+ [PutFunctionConcurrency](API_PutFunctionConcurrency.md) -+ [DeleteFunctionConcurrency](API_DeleteFunctionConcurrency.md) -+ [ListTags](API_ListTags.md) -+ [TagResource](API_TagResource.md) -+ [UntagResource](API_UntagResource.md) - -To grant other accounts permission for multiple functions, or for actions that don't operate on a function, use [roles](access-control-identity-based.md)\. - -## Granting layer access to other accounts - -To grant layer\-usage permission to another account, add a statement to the layer version's permissions policy with the `add-layer-version-permission` command\. In each statement, you can grant permission to a single account, all accounts, or an organization\. - -``` -$ aws lambda add-layer-version-permission --layer-name xray-sdk-nodejs --statement-id xaccount \ ---action lambda:GetLayerVersion --principal 210987654321 --version-number 1 --output text -e210ffdc-e901-43b0-824b-5fcd0dd26d16 {"Sid":"xaccount","Effect":"Allow","Principal":{"AWS":"arn:aws:iam::210987654321:root"},"Action":"lambda:GetLayerVersion","Resource":"arn:aws:lambda:us-east-2:123456789012:layer:xray-sdk-nodejs:1"} -``` - -Permissions only apply to a single version of a layer\. Repeat the procedure each time you create a new layer version\. - -To grant permission to all accounts in an organization, use the `organization-id` option\. The following example grants all accounts in an organization permission to use version 3 of a layer\. - -``` -$ aws lambda add-layer-version-permission --layer-name my-layer \ ---statement-id engineering-org --version-number 3 --principal '*' \ ---action lambda:GetLayerVersion --organization-id o-t194hfs8cz --output text -b0cd9796-d4eb-4564-939f-de7fe0b42236 {"Sid":"engineering-org","Effect":"Allow","Principal":"*","Action":"lambda:GetLayerVersion","Resource":"arn:aws:lambda:us-east-2:123456789012:layer:my-layer:3","Condition":{"StringEquals":{"aws:PrincipalOrgID":"o-t194hfs8cz"}}}" -``` - -To grant permission to all AWS accounts, use `*` for the principal, and omit the organization ID\. For multiple accounts or organizations, add multiple statements\. - -## Cleaning up resource\-based policies - -To view a function's resource\-based policy, use the `get-policy` command\. - -``` -$ aws lambda get-policy --function-name my-function --output text -{"Version":"2012-10-17","Id":"default","Statement":[{"Sid":"sns","Effect":"Allow","Principal":{"Service":"s3.amazonaws.com"},"Action":"lambda:InvokeFunction","Resource":"arn:aws:lambda:us-east-2:123456789012:function:my-function","Condition":{"ArnLike":{"AWS:SourceArn":"arn:aws:sns:us-east-2:123456789012:lambda*"}}}]} 7c681fc9-b791-4e91-acdf-eb847fdaa0f0 -``` - -For versions and aliases, append the version number or alias to the function name\. - -``` -$ aws lambda get-policy --function-name my-function:PROD -``` - -To remove permissions from your function, use `remove-permission`\. - -``` -$ aws lambda remove-permission --function-name example --statement-id sns -``` - -Use the `get-layer-version-policy` command to view the permissions on a layer\. Use `remove-layer-version-permission` to remove statements from the policy\. - -``` -$ aws lambda get-layer-version-policy --layer-name my-layer --version-number 3 --output text -b0cd9796-d4eb-4564-939f-de7fe0b42236 {"Sid":"engineering-org","Effect":"Allow","Principal":"*","Action":"lambda:GetLayerVersion","Resource":"arn:aws:lambda:us-west-2:123456789012:layer:my-layer:3","Condition":{"StringEquals":{"aws:PrincipalOrgID":"o-t194hfs8cz"}}}" - -$ aws lambda remove-layer-version-permission --layer-name my-layer --version-number 3 --statement-id engineering-org -``` \ No newline at end of file diff --git a/doc_source/applications-console.md b/doc_source/applications-console.md deleted file mode 100644 index 00a0c14a..00000000 --- a/doc_source/applications-console.md +++ /dev/null @@ -1,91 +0,0 @@ -# Managing applications in the AWS Lambda console - -The AWS Lambda console helps you monitor and manage your [Lambda applications](deploying-lambda-apps.md)\. The **Applications** menu lists AWS CloudFormation stacks with Lambda functions\. The menu includes stacks that you launch in AWS CloudFormation by using the AWS CloudFormation console, the AWS Serverless Application Repository, the AWS CLI, or the AWS SAM CLI\. - -**To view a Lambda application** - -1. Open the Lambda console [Applications page](https://console.aws.amazon.com/lambda/home#/applications)\. - -1. Choose an application\. -![\[A monitoring widget.\]](http://docs.aws.amazon.com/lambda/latest/dg/images/applications-page.png) - -The overview shows the following information about your application\. -+ **AWS CloudFormation template** or **SAM template** – The template that defines your application\. -+ **Resources** – The AWS resources that are defined in your application's template\. To manage your application's Lambda functions, choose a function name from the list\. - -## Monitoring applications - -The **Monitoring** tab shows an Amazon CloudWatch dashboard with aggregate metrics for the resources in your application\. - -**To monitor a Lambda application** - -1. Open the Lambda console [Applications page](https://console.aws.amazon.com/lambda/home#/applications)\. - -1. Choose **Monitoring**\. - -By default, the Lambda console shows a basic dashboard\. You can customize this page by defining custom dashboards in your application template\. When your template includes one or more dashboards, the page shows your dashboards instead of the default dashboard\. You can switch between dashboards with the drop\-down menu on the top right of the page\. - -## Custom monitoring dashboards - -Customize your application monitoring page by adding one or more Amazon CloudWatch dashboards to your application template with the [AWS::CloudWatch::Dashboard](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-dashboard.html) resource type\. The following example creates a dashboard with a single widget that graphs the number of invocations of a function named `my-function`\. - -**Example Function dashboard template** - -``` -Resources: - MyDashboard: - Type: AWS::CloudWatch::Dashboard - Properties: - DashboardName: my-dashboard - DashboardBody: | - { - "widgets": [ - { - "type": "metric", - "width": 12, - "height": 6, - "properties": { - "metrics": [ - [ - "AWS/Lambda", - "Invocations", - "FunctionName", - "my-function", - { - "stat": "Sum", - "label": "MyFunction" - } - ], - [ - { - "expression": "SUM(METRICS())", - "label": "Total Invocations" - } - ] - ], - "region": "us-east-1", - "title": "Invocations", - "view": "timeSeries", - "stacked": false - } - } - ] - } -``` - -You can get the definition for any of the widgets in the default monitoring dashboard from the CloudWatch console\. - -**To view a widget definition** - -1. Open the Lambda console [Applications page](https://console.aws.amazon.com/lambda/home#/applications)\. - -1. Choose an application that has the standard dashboard\. - -1. Choose **Monitoring**\. - -1. On any widget, choose **View in metrics** from the drop\-down menu\. -![\[A monitoring widget.\]](http://docs.aws.amazon.com/lambda/latest/dg/images/applications-monitoring-widget.png) - -1. Choose **Source**\. - -For more information about authoring CloudWatch dashboards and widgets, see [Dashboard body structure and syntax](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/CloudWatch-Dashboard-Body-Structure.html) in the *Amazon CloudWatch API Reference*\. \ No newline at end of file diff --git a/doc_source/applications-tutorial.md b/doc_source/applications-tutorial.md deleted file mode 100644 index f029d9ce..00000000 --- a/doc_source/applications-tutorial.md +++ /dev/null @@ -1,317 +0,0 @@ -# Creating an application with continuous delivery in the Lambda console - -You can use the Lambda console to create an application with an integrated continuous delivery pipeline\. With continuous delivery, every change that you push to your source control repository triggers a pipeline that builds and deploys your application automatically\. The Lambda console provides starter projects for common application types with Node\.js sample code and templates that create supporting resources\. - -In this tutorial, you create the following resources\. -+ **Application** – A Node\.js Lambda function, build specification, and AWS Serverless Application Model \(AWS SAM\) template\. -+ **Pipeline** – An AWS CodePipeline pipeline that connects the other resources to enable continuous delivery\. -+ **Repository** – A Git repository in AWS CodeCommit\. When you push a change, the pipeline copies the source code into an Amazon S3 bucket and passes it to the build project\. -+ **Trigger** – An Amazon CloudWatch Events rule that watches the master branch of the repository and triggers the pipeline\. -+ **Build project** – An AWS CodeBuild build that gets the source code from the pipeline and packages the application\. The source includes a build specification with commands that install dependencies and prepare the application template for deployment\. -+ **Deployment configuration** – The pipeline's deployment stage defines a set of actions that take the processed AWS SAM template from the build output, and deploy the new version with AWS CloudFormation\. -+ **Bucket** – An Amazon Simple Storage Service \(Amazon S3\) bucket for deployment artifact storage\. -+ **Roles** – The pipeline's source, build, and deploy stages have IAM roles that allow them to manage AWS resources\. The application's function has an [execution role](lambda-intro-execution-role.md) that allows it to upload logs and can be extended to access other services\. - -Your application and pipeline resources are defined in AWS CloudFormation templates that you can customize and extend\. Your application repository includes a template that you can modify to add Amazon DynamoDB tables, an Amazon API Gateway API, and other application resources\. The continuous delivery pipeline is defined in a separate template outside of source control and has its own stack\. - -The pipeline maps a single branch in a repository to a single application stack\. You can create additional pipelines to add environments for other branches in the same repository\. You can also add stages to your pipeline for testing, staging, and manual approvals\. For more information about AWS CodePipeline, see [What is AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)\. - -**Topics** -+ [Prerequisites](#applications-tutorial-prepare) -+ [Create an application](#applications-tutorial-wizard) -+ [Invoke the function](#applications-tutorial-invoke) -+ [Add an AWS resource](#applications-tutorial-update) -+ [Update the permissions boundary](#applications-tutorial-permissions) -+ [Update the function code](#applications-tutorial-code) -+ [Next steps](#applications-tutorial-nextsteps) -+ [Troubleshooting](#applications-tutorial-troubleshooting) -+ [Clean up](#applications-tutorial-cleanup) - -## Prerequisites - -This tutorial assumes that you have some knowledge of basic Lambda operations and the Lambda console\. If you haven't already, follow the instructions in [Getting started with AWS Lambda](getting-started.md) to create your first Lambda function\. - -To follow the procedures in this guide, you will need a command line terminal or shell to run commands\. Commands are shown in listings preceded by a prompt symbol \($\) and the name of the current directory, when appropriate: - -``` -~/lambda-project$ this is a command -this is output -``` - -For long commands, an escape character \(`\`\) is used to split a command over multiple lines\. - -On Linux and macOS, use your preferred shell and package manager\. On Windows 10, you can [install the Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows\-integrated version of Ubuntu and Bash\. - -This tutorial uses CodeCommit for source control\. To set up your local machine to access and update application code, see [Setting up](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up.html) in the *AWS CodeCommit User Guide*\. - -## Create an application - -Create an application in the Lambda console\. - -**To create an application** - -1. Open the Lambda console [Applications page](https://console.aws.amazon.com/lambda/home#/applications)\. - -1. Choose **Create application**\. - -1. Choose **Author from scratch**\. - -1. Configure application settings\. - + **Application name** – **my\-app**\. - + **Application description** – **my application**\. - + **Runtime** – **Node\.js 10\.x**\. - + **Source control service** – **CodeCommit**\. - + **Repository name** – **my\-app\-repo**\. - + **Permissions** – **Create roles and permissions boundary**\. - -1. Choose **Create**\. - -Lambda creates the pipeline and related resources and commits the sample application code to the Git repository\. As resources are created, they appear on the overview page\. - -## Invoke the function - -Invoke the function to verify that it works\. - -**To invoke the application's function** - -1. Open the Lambda console [Applications page](https://console.aws.amazon.com/lambda/home#/applications)\. - -1. Choose **my\-app**\. - -1. Under **Resources**, choose **helloFromLambdaFunction**\. - -1. Choose **Test**\. - -1. Configure a test event\. - + **Event name** – **test** - + **Body** – **\{\}** - -1. Choose **Create**\. - -1. Choose **Test**\. - -The Lambda console executes your function and displays the result\. Expand the **Details** section under the result to see the output and execution details\. - -## Add an AWS resource - -When you create your application, the Lambda console creates a Git repository that contains the sample application\. To get a copy of the application code on your local machine, clone the project repository\. - -**To clone the project repository** - -1. Open the Lambda console [Applications page](https://console.aws.amazon.com/lambda/home#/applications)\. - -1. Choose **my\-app**\. - -1. Choose **Code**\. - -1. Under **Repository details**, copy the HTTP or SSH repository URI, depending on the authentication mode that you configured during [setup](#applications-tutorial-prepare)\. - -1. Clone the repository\. - - ``` - ~$ git clone ssh://git-codecommit.us-east-2.amazonaws.com/v1/repos/my-app-repo - ``` - -The repository contains the template for the application, a build specification, and code\. Add a DynamoDB table to the application template\. - -**To add a DynamoDB table** - -1. Open `template.yml` in a text editor\. - -1. Add a table resource, an environment variable that passes the table name to the function, and a permissions policy that allows the function to manage it\. -**Example template\.yml \- resources** - - ``` - ... - Resources: - ddbTable: - Type: AWS::Serverless::SimpleTable - Properties: - PrimaryKey: - Name: id - Type: String - ProvisionedThroughput: - ReadCapacityUnits: 1 - WriteCapacityUnits: 1 - helloFromLambdaFunction: - Type: AWS::Serverless::Function - Properties: - Handler: src/handlers/hello-from-lambda.helloFromLambdaHandler - Runtime: nodejs10.x - MemorySize: 128 - Timeout: 100 - Description: This is a hello from Lambda example. - Environment: - Variables: - DDB_TABLE: !Ref ddbTable - Policies: - - DynamoDBCrudPolicy: - TableName: !Ref ddbTable - - AWSLambdaBasicExecutionRole - ``` - -1. Commit and push the change\. - - ``` - ~/my-app-repo$ git commit -am "Add DynamoDB table" - ~/my-app-repo$ git push - ``` - -When you push a change, it triggers the application's pipeline\. Use the **Deployments** tab of the application screen to track the change as it flows through the pipeline\. When the deployment is complete, proceed to the next step\. - -## Update the permissions boundary - -The sample application applies a *permissions boundary* to its function's execution role\. The permissions boundary limits the permissions that you can add to the function's role\. Without the boundary, users with write access to the project repository could modify the project template to give the function permission to access resources and services outside of the scope of the sample application\. - -In order for the function to use the DynamoDB permission that you added to its execution role in the previous step, you must extend the permissions boundary to allow the additional permissions\. The Lambda console detects resources that aren't in the permissions boundary and provides an updated policy that you can use to update it\. - -**To update the application's permissions boundary** - -1. Open the Lambda console [Applications page](https://console.aws.amazon.com/lambda/home#/applications)\. - -1. Choose your application\. - -1. Under **Resources**, choose **Edit permissions boundary**\. - -1. Follow the instructions shown to update the boundary to allow access to the new table\. - -For more information about permissions boundaries, see [Using permissions boundaries for AWS Lambda applications](permissions-boundary.md)\. - -## Update the function code - -Next, update the function code to use the table\. The following code uses the table to track the number of invocations processed by each instance of the function\. It uses the log stream ID as a unique identifier\. New instances are created when you update a function, and to handle multiple concurrent invocations\. - -**To update the function code** - -1. Add a new handler named `index.js` to the `src/handlers` folder with the following content\. -**Example src/handlers/index\.js** - - ``` - const dynamodb = require('aws-sdk/clients/dynamodb'); - const docClient = new dynamodb.DocumentClient(); - - exports.handler = async (event, context) => { - const message = 'Hello from Lambda!'; - const tableName = process.env.DDB_TABLE; - const logStreamName = context.logStreamName; - var params = { - TableName : tableName, - Key: { id : logStreamName }, - UpdateExpression: 'set invocations = if_not_exists(invocations, :start) + :inc', - ExpressionAttributeValues: { - ':start': 0, - ':inc': 1 - }, - ReturnValues: 'ALL_NEW' - }; - await docClient.update(params).promise(); - - const response = { - body: JSON.stringify(message) - }; - console.log(`body: ${response.body}`); - return response; - } - ``` - -1. Open the application template and change the handler value to `src/handlers/index.handler`\. -**Example template\.yml** - - ``` - ... - helloFromLambdaFunction: - Type: AWS::Serverless::Function - Properties: - Handler: src/handlers/index.handler - Runtime: nodejs10.x - ``` - -1. Commit and push the change\. - - ``` - ~/my-app-repo$ git add . && git commit -m "Use DynamoDB table" - ~/my-app-repo$ git push - ``` - -After the code change is deployed, invoke the function a few times to update the DynamoDB table\. - -**To view the DynamoDB table** - -1. Open the [Tables page of the DynamoDB console](https://console.aws.amazon.com/dynamodb/home#tables:)\. - -1. Choose the table that starts with **my\-app**\. - -1. Choose **Items**\. - -1. Choose **Start search**\. - -## Next steps - -The AWS CloudFormation template that defines your application resources uses the AWS Serverless Application Model transform to simplify the syntax for resource definitions, and automate uploading the deployment package and other artifacts\. AWS SAM also provides a command line interface \(the AWS SAM CLI\), which has the same packaging and deployment functionality as the AWS CLI, with additional features specific to Lambda applications\. Use the AWS SAM CLI to test your application locally in a Docker container that emulates the Lambda execution environment\. -+ [Installing the AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) -+ [Testing and debugging serverless applications](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-test-and-debug.html) - -AWS Cloud9 provides an online development environment that includes Node\.js, the AWS SAM CLI, and Docker\. With AWS Cloud9, you can start developing quickly and access your development environment from any computer\. For instructions, see [Getting started](https://docs.aws.amazon.com/cloud9/latest/user-guide/get-started.html) in the *AWS Cloud9 User Guide*\. - -For local development, AWS toolkits for integrated development environments \(IDEs\) let you test and debug functions before pushing them to your repository\. -+ [AWS Toolkit for JetBrains](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/) – Plugin for PyCharm \(Python\) and IntelliJ \(Java\) IDEs\. -+ [AWS Toolkit for Eclipse](https://docs.aws.amazon.com/AWSToolkitEclipse/latest/GettingStartedGuide/) – Plugin for Eclipse IDE \(multiple languages\)\. -+ [AWS Toolkit for Visual Studio Code](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/) – Plugin for Visual Studio Code IDE \(multiple languages\)\. -+ [AWS Toolkit for Visual Studio](https://docs.aws.amazon.com/AWSToolkitVS/latest/UserGuide/) – Plugin for Visual Studio IDE \(multiple languages\)\. - -## Troubleshooting - -As you develop your application, you will likely encounter the following types of errors\. -+ **Build errors** – Issues that occur during the build phase, including compilation, test, and packaging errors\. -+ **Deployment errors** – Issues that occur when AWS CloudFormation isn't able to update the application stack\. These include permissions errors, account limits, service issues, or template errors\. -+ **Invocation errors** – Errors that are returned by a function's code or runtime\. - -For build and deployment errors, you can identify the cause of an error in the Lambda console\. - -**To troubleshoot application errors** - -1. Open the Lambda console [Applications page](https://console.aws.amazon.com/lambda/home#/applications)\. - -1. Choose an application\. - -1. Choose **Deployments**\. - -1. To view the application's pipeline, choose **Deployment pipeline**\. - -1. Identify the action that encountered an error\. - -1. To view the error in context, choose **Details**\. - -For deployment errors that occur during the **ExecuteChangeSet** action, the pipeline links to a list of stack events in the AWS CloudFormation console\. Search for an event with the status **UPDATE\_FAILED**\. Because AWS CloudFormation rolls back after an error, the relevant event is under several other events in the list\. If AWS CloudFormation could not create a change set, the error appears under **Change sets** instead of under **Events**\. - -A common cause of deployment and invocation errors is a lack of permissions in one or more roles\. The pipeline has a role for deployments \(`CloudFormationRole`\) that's equivalent to the [user permissions](access-control-identity-based.md) that you would use to update an AWS CloudFormation stack directly\. If you add resources to your application or enable Lambda features that require user permissions, the deployment role is used\. You can find a link to the deployment role under **Infrastructure** in the application overview\. - -If your function accesses other AWS services or resources, or if you enable features that require the function to have additional permissions, the function's [execution role](lambda-intro-execution-role.md) is used\. All execution roles that are created in your application template are also subject to the application's permissions boundary\. This boundary requires you to explicitly grant access to additional services and resources in IAM after adding permissions to the execution role in the template\. - -For example, to [connect a function to a virtual private cloud](configuration-vpc.md) \(VPC\), you need user permissions to describe VPC resources\. The execution role needs permission to manage network interfaces\. This requires the following steps\. - -1. Add the required user permissions to the deployment role in IAM\. - -1. Add the execution role permissions to the permissions boundary in IAM\. - -1. Add the execution role permissions to the execution role in the application template\. - -1. Commit and push to deploy the updated execution role\. - -After you address permissions errors, choose **Release change** in the pipeline overview to rerun the build and deployment\. - -## Clean up - -You can continue to modify and use the sample to develop your own application\. If you are done using the sample, delete the application to avoid paying for the pipeline, repository, and storage\. - -**To delete the application** - -1. Open the [AWS CloudFormation console](https://console.aws.amazon.com/cloudformation)\. - -1. Delete the application stack – **my\-app**\. - -1. Open the [Amazon S3 console](https://console.aws.amazon.com/s3)\. - -1. Delete the artifact bucket – **aws\-*us\-east\-2*\-*123456789012*\-my\-app\-pipe**\. - -1. Return to the AWS CloudFormation console and delete the infrastructure stack – **serverlessrepo\-my\-app\-toolchain**\. \ No newline at end of file diff --git a/doc_source/applications-usecases.md b/doc_source/applications-usecases.md deleted file mode 100644 index 9de9c162..00000000 --- a/doc_source/applications-usecases.md +++ /dev/null @@ -1,49 +0,0 @@ -# Common Lambda application types and use cases - -When building applications on AWS Lambda the core components are Lambda functions and triggers\. A trigger is the AWS service or application that invokes a function, and a Lambda function is the code and runtime that process events\. To illustrate, consider the following scenarios: -+ **File processing** – Suppose you have a photo sharing application\. People use your application to upload photos, and the application stores these user photos in an Amazon S3 bucket\. Then, your application creates a thumbnail version of each user's photos and displays them on the user's profile page\. In this scenario, you may choose to create a Lambda function that creates a thumbnail automatically\. Amazon S3 is one of the supported AWS event sources that can publish *object\-created events* and invoke your Lambda function\. Your Lambda function code can read the photo object from the S3 bucket, create a thumbnail version, and then save it in another S3 bucket\. -+ **Data and analytics** – Suppose you are building an analytics application and storing raw data in a DynamoDB table\. When you write, update, or delete items in a table, DynamoDB streams can publish item update events to a stream associated with the table\. In this case, the event data provides the item key, event name \(such as insert, update, and delete\), and other relevant details\. You can write a Lambda function to generate custom metrics by aggregating raw data\. -+ **Websites** – Suppose you are creating a website and you want to host the backend logic on Lambda\. You can invoke your Lambda function over HTTP using Amazon API Gateway as the HTTP endpoint\. Now, your web client can invoke the API, and then API Gateway can route the request to Lambda\. -+ **Mobile applications** – Suppose you have a custom mobile application that produces events\. You can create a Lambda function to process events published by your custom application\. For example, in this scenario you can configure a Lambda function to process the clicks within your custom mobile application\. - -AWS Lambda supports many AWS services as event sources\. For more information, see [Using AWS Lambda with other services](lambda-services.md)\. When you configure these event sources to trigger a Lambda function, the Lambda function is invoked automatically when events occur\. You define *event source mapping*, which is how you identify what events to track and which Lambda function to invoke\. - -The following are introductory examples of event sources and how the end\-to\-end experience works\. - -## Example 1: Amazon S3 pushes events and invokes a Lambda function - -Amazon S3 can publish events of different types, such as PUT, POST, COPY, and DELETE object events on a bucket\. Using the bucket notification feature, you can configure an event source mapping that directs Amazon S3 to invoke a Lambda function when a specific type of event occurs, as shown in the following illustration\. - -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/push-s3-example-10.png) - -The diagram illustrates the following sequence: - -1. The user creates an object in a bucket\. - -1. Amazon S3 detects the object created event\. - -1. Amazon S3 invokes your Lambda function using the permissions provided by the [execution role](lambda-intro-execution-role.md)\. - -1. AWS Lambda executes the Lambda function, specifying the event as a parameter\. - -You configure Amazon S3 to invoke your function as a bucket notification action\. To grant Amazon S3 permission to invoke the function, update the function's [resource\-based policy](access-control-resource-based.md)\. - -## Example 2: AWS Lambda pulls events from a Kinesis stream and invokes a Lambda function - -For poll\-based event sources, AWS Lambda polls the source and then invokes the Lambda function when records are detected on that source\. -+ [CreateEventSourceMapping](API_CreateEventSourceMapping.md) -+ [UpdateEventSourceMapping](API_UpdateEventSourceMapping.md) - -The following diagram shows how a custom application writes records to a Kinesis stream\. - -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/kinesis-pull-10.png) - -The diagram illustrates the following sequence: - -1. The custom application writes records to a Kinesis stream\. - -1. AWS Lambda continuously polls the stream, and invokes the Lambda function when the service detects new records on the stream\. AWS Lambda knows which stream to poll and which Lambda function to invoke based on the event source mapping you create in Lambda\. - -1. The Lambda function is invoked with the incoming event\. - -When working with stream\-based event sources, you create event source mappings in AWS Lambda\. Lambda reads items from the stream invokes the function synchronously\. You don't need to grant Lambda permission to invoke the function, but it does need permission to read from the stream\. \ No newline at end of file diff --git a/doc_source/best-practices.md b/doc_source/best-practices.md deleted file mode 100644 index bb9d9513..00000000 --- a/doc_source/best-practices.md +++ /dev/null @@ -1,62 +0,0 @@ -# Best Practices for Working with AWS Lambda Functions - -The following are recommended best practices for using AWS Lambda: - -**Topics** -+ [Function Code](#function-code) -+ [Function Configuration](#function-configuration) -+ [Alarming and Metrics](#alarming-metrics) -+ [Stream Event Invokes](#stream-events) - -## Function Code -+ **Separate the Lambda handler from your core logic\.** This allows you to make a more unit\-testable function\. In Node\.js this may look like: - - ``` - exports.myHandler = function(event, context, callback) { - var foo = event.foo; - var bar = event.bar; - var result = MyLambdaFunction (foo, bar); - - callback(null, result); - } - - function MyLambdaFunction (foo, bar) { - // MyLambdaFunction logic here - } - ``` -+ **Take advantage of execution context reuse to improve the performance of your function\.** Initialize SDK clients and database connections outside of the function handler, and cache static assets locally in the `/tmp` directory\. Subsequent invocations processed by the same instance of your function can reuse these resources\. This saves execution time and cost\. - - To avoid potential data leaks across invocations, don’t use the execution context to store user data, events, or other information with security implications\. If your function relies on a mutable state that can’t be stored in memory within the handler, consider creating a separate function or separate versions of a function for each user\. -+ **Use [environment variables](configuration-envvars.md) to pass operational parameters to your function\.** For example, if you are writing to an Amazon S3 bucket, instead of hard\-coding the bucket name you are writing to, configure the bucket name as an environment variable\. -+ **Control the dependencies in your function's deployment package\. ** The AWS Lambda execution environment contains a number of libraries such as the AWS SDK for the Node\.js and Python runtimes \(a full list can be found here: [AWS Lambda runtimes](lambda-runtimes.md)\)\. To enable the latest set of features and security updates, Lambda will periodically update these libraries\. These updates may introduce subtle changes to the behavior of your Lambda function\. To have full control of the dependencies your function uses, package all of your dependencies with your deployment package\. -+ **Minimize your deployment package size to its runtime necessities\. ** This will reduce the amount of time that it takes for your deployment package to be downloaded and unpacked ahead of invocation\. For functions authored in Java or \.NET Core, avoid uploading the entire AWS SDK library as part of your deployment package\. Instead, selectively depend on the modules which pick up components of the SDK you need \(e\.g\. DynamoDB, Amazon S3 SDK modules and [Lambda core libraries](https://github.com/aws/aws-lambda-java-libs)\)\. -+ **Reduce the time it takes Lambda to unpack deployment packages** authored in Java by putting your dependency `.jar` files in a separate /lib directory\. This is faster than putting all your function’s code in a single jar with a large number of `.class` files\. See [AWS Lambda deployment package in Java](java-package.md) for instructions\. -+ **Minimize the complexity of your dependencies\.** Prefer simpler frameworks that load quickly on [execution context](runtimes-context.md) startup\. For example, prefer simpler Java dependency injection \(IoC\) frameworks like [Dagger](https://google.github.io/dagger/) or [Guice](https://github.com/google/guice), over more complex ones like [Spring Framework](https://github.com/spring-projects/spring-framework)\. -+ **Avoid using recursive code** in your Lambda function, wherein the function automatically calls itself until some arbitrary criteria is met\. This could lead to unintended volume of function invocations and escalated costs\. If you do accidentally do so, set the function concurrent execution limit to `0` immediately to throttle all invocations to the function, while you update the code\. - -## Function Configuration -+ **Performance testing your Lambda function** is a crucial part in ensuring you pick the optimum memory size configuration\. Any increase in memory size triggers an equivalent increase in CPU available to your function\. The memory usage for your function is determined per\-invoke and can be viewed in [AWS CloudWatch Logs](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatchLogs.html)\. On each invoke a `REPORT:` entry will be made, as shown below: - - ``` - REPORT RequestId: 3604209a-e9a3-11e6-939a-754dd98c7be3 Duration: 12.34 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 18 MB - ``` - - By analyzing the `Max Memory Used:` field, you can determine if your function needs more memory or if you over\-provisioned your function's memory size\. -+ **Load test your Lambda function** to determine an optimum timeout value\. It is important to analyze how long your function runs so that you can better determine any problems with a dependency service that may increase the concurrency of the function beyond what you expect\. This is especially important when your Lambda function makes network calls to resources that may not handle Lambda's scaling\. -+ **Use most\-restrictive permissions when setting IAM policies\.** Understand the resources and operations your Lambda function needs, and limit the execution role to these permissions\. For more information, see [AWS Lambda permissions](lambda-permissions.md)\. -+ **Be familiar with [AWS Lambda limits](gettingstarted-limits.md)\.** Payload size, file descriptors and /tmp space are often overlooked when determining runtime resource limits\. -+ **Delete Lambda functions that you are no longer using\.** By doing so, the unused functions won't needlessly count against your deployment package size limit\. -+ **If you are using Amazon Simple Queue Service** as an event source, make sure the value of the function's expected execution time does not exceed the [Visibility Timeout](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html) value on the queue\. This applies both to [CreateFunction](API_CreateFunction.md) and [UpdateFunctionConfiguration](API_UpdateFunctionConfiguration.md)\. - + In the case of **CreateFunction**, AWS Lambda will fail the function creation process\. - + In the case of **UpdateFunctionConfiguration**, it could result in duplicate invocations of the function\. - -## Alarming and Metrics -+ **Use [Working with AWS Lambda function metrics](monitoring-metrics.md) and [ CloudWatch Alarms](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html)** instead of creating or updating a metric from within your Lambda function code\. It's a much more efficient way to track the health of your Lambda functions, allowing you to catch issues early in the development process\. For instance, you can configure an alarm based on the expected duration of your Lambda function execution time in order to address any bottlenecks or latencies attributable to your function code\. -+ **Leverage your logging library and [AWS Lambda Metrics and Dimensions](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/lam-metricscollected.html)** to catch app errors \(e\.g\. ERR, ERROR, WARNING, etc\.\) - -## Stream Event Invokes -+ **Test with different batch and record sizes **so that the polling frequency of each event source is tuned to how quickly your function is able to complete its task\. [BatchSize](API_CreateEventSourceMapping.md#SSS-CreateEventSourceMapping-request-BatchSize) controls the maximum number of records that can be sent to your function with each invoke\. A larger batch size can often more efficiently absorb the invoke overhead across a larger set of records, increasing your throughput\. - - By default, Lambda invokes your function as soon as records are available in the stream\. If the batch it reads from the stream only has one record in it, Lambda only sends one record to the function\. To avoid invoking the function with a small number of records, you can tell the event source to buffer records for up to 5 minutes by configuring a *batch window*\. Before invoking the function, Lambda continues to read records from the stream until it has gathered a full batch, or until the batch window expires\. -+ **Increase Kinesis stream processing throughput by adding shards\.** A Kinesis stream is composed of one or more shards\. Lambda will poll each shard with at most one concurrent invocation\. For example, if your stream has 100 active shards, there will be at most 100 Lambda function invocations running concurrently\. Increasing the number of shards will directly increase the number of maximum concurrent Lambda function invocations and can increase your Kinesis stream processing throughput\. If you are increasing the number of shards in a Kinesis stream, make sure you have picked a good partition key \(see [Partition Keys](https://docs.aws.amazon.com/streams/latest/dev/key-concepts.html#partition-key)\) for your data, so that related records end up on the same shards and your data is well distributed\. -+ **Use [Amazon CloudWatch](https://docs.aws.amazon.com/streams/latest/dev/monitoring-with-cloudwatch.html)** on IteratorAge to determine if your Kinesis stream is being processed\. For example, configure a CloudWatch alarm with a maximum setting to 30000 \(30 seconds\)\. \ No newline at end of file diff --git a/doc_source/build-pipeline.md b/doc_source/build-pipeline.md deleted file mode 100644 index 832a1304..00000000 --- a/doc_source/build-pipeline.md +++ /dev/null @@ -1,290 +0,0 @@ -# Building a continuous delivery pipeline for a Lambda application with AWS CodePipeline - -You can use AWS CodePipeline to create a continuous delivery pipeline for your Lambda application\. CodePipeline combines source control, build, and deployment resources to create a pipeline that runs whenever you make a change to your application's source code\. - -In this tutorial, you create the following resources\. -+ **Repository** – A Git repository in AWS CodeCommit\. When you push a change, the pipeline copies the source code into an Amazon S3 bucket and passes it to the build project\. -+ **Build project** – An AWS CodeBuild build that gets the source code from the pipeline and packages the application\. The source includes a build specification with commands that install dependencies and prepare an AWS Serverless Application Model \(AWS SAM\) template for deployment\. -+ **Deployment configuration** – The pipeline's deployment stage defines a set of actions that take the AWS SAM template from the build output, create a change set in AWS CloudFormation, and execute the change set to update the application's AWS CloudFormation stack\. -+ **AWS CloudFormation stack** – The deployment stage uses a template to create a stack in AWS CloudFormation\. The template is a YAML\-formatted document that defines the resources of the Lambda application\. The application includes a Lambda function and an Amazon API Gateway API that invokes it\. -+ **Roles** – The pipeline, build, and deployment each have a service role that allows them to manage AWS resources\. The console creates the pipeline and build roles when you create those resources\. You create the role that allows AWS CloudFormation to manage the application stack\. - -The pipeline maps a single branch in a repository to a single AWS CloudFormation stack\. You can create additional pipelines to add environments for other branches in the same repository\. You can also add stages to your pipeline for testing, staging, and manual approvals\. For more information about AWS CodePipeline, see [What is AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)\. - -For an alternate method of creating a pipeline with AWS Serverless Application Model and AWS CloudFormation, watch [Automate your serverless application deployments](https://www.youtube.com/watch?v=0o3urdBeoII) on the Amazon Web Services YouTube channel\. - -**Topics** -+ [Prerequisites](#with-pipeline-prepare) -+ [Create an AWS CloudFormation role](#with-pipeline-create-cfn-role) -+ [Set up a repository](#setup-repository) -+ [Create a pipeline](#create-pipeline1) -+ [Update the build stage role](#update-policy) -+ [Complete the deployment stage](#create-pipeline2) -+ [Test the application](#applications-pipeline-test) - -## Prerequisites - -This tutorial assumes that you have some knowledge of basic Lambda operations and the Lambda console\. If you haven't already, follow the instructions in [Getting started with AWS Lambda](getting-started.md) to create your first Lambda function\. - -To follow the procedures in this guide, you will need a command line terminal or shell to run commands\. Commands are shown in listings preceded by a prompt symbol \($\) and the name of the current directory, when appropriate: - -``` -~/lambda-project$ this is a command -this is output -``` - -For long commands, an escape character \(`\`\) is used to split a command over multiple lines\. - -On Linux and macOS, use your preferred shell and package manager\. On Windows 10, you can [install the Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows\-integrated version of Ubuntu and Bash\. - -During the build phase, the build script uploads artifacts to Amazon Simple Storage Service \(Amazon S3\)\. You can use an existing bucket, or create a new bucket for the pipeline\. Use the AWS CLI to create a bucket\. - -``` -$ aws s3 mb s3://lambda-deployment-artifacts-123456789012 -``` - -## Create an AWS CloudFormation role - -Create a role that gives AWS CloudFormation permission to access AWS resources\. - -**To create an AWS CloudFormation role** - -1. Open the [roles page](https://console.aws.amazon.com/iam/home#/roles) in the IAM console\. - -1. Choose **Create role**\. - -1. Create a role with the following properties\. - + **Trusted entity** – **AWS CloudFormation** - + **Permissions** – **AWSLambdaExecute** - + **Role name** – **cfn\-lambda\-pipeline** - -1. Open the role\. Under the **Permissions** tab, choose **Add inline policy**\. - -1. In **Create Policy**, choose the **JSON** tab and add the following policy\. - - ``` - { - "Statement": [ - { - "Action": [ - "apigateway:*", - "codedeploy:*", - "lambda:*", - "cloudformation:CreateChangeSet", - "iam:GetRole", - "iam:CreateRole", - "iam:DeleteRole", - "iam:PutRolePolicy", - "iam:AttachRolePolicy", - "iam:DeleteRolePolicy", - "iam:DetachRolePolicy", - "iam:PassRole", - "s3:GetObject", - "s3:GetObjectVersion", - "s3:GetBucketVersioning" - ], - "Resource": "*", - "Effect": "Allow" - } - ], - "Version": "2012-10-17" - } - ``` - -## Set up a repository - -Create an AWS CodeCommit repository to store your project files\. For more information, see [Setting up](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up.html) in the CodeCommit User Guide\. - -**To create a repository** - -1. Open the [Developer tools console](https://console.aws.amazon.com/codesuite/home)\. - -1. Under **Source**, choose **Repositories**\. - -1. Choose **Create repository**\. - -1. Follow the instructions to create and clone a repository named **lambda\-pipeline\-repo**\. - -Create the following files in the repository folder\. - -**Example index\.js** -A Lambda function that returns the current time\. - -``` -var time = require('time'); -exports.handler = (event, context, callback) => { - var currentTime = new time.Date(); - currentTime.setTimezone("America/Los_Angeles"); - callback(null, { - statusCode: '200', - body: 'The time in Los Angeles is: ' + currentTime.toString(), - }); -}; -``` - -**Example template\.yml** -The [AWS SAM template](gettingstarted-tools.md) that defines the application\. - -``` -AWSTemplateFormatVersion: '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Description: Outputs the time -Resources: - TimeFunction: - Type: AWS::Serverless::Function - Properties: - Handler: index.handler - Runtime: nodejs10.x - CodeUri: ./ - Events: - MyTimeApi: - Type: Api - Properties: - Path: /TimeResource - Method: GET -``` - -**Example buildspec\.yml** -An [AWS CodeBuild build specification](https://docs.aws.amazon.com/codebuild/latest/userguide/build-spec-ref.html) that installs required packages and uploads the deployment package to Amazon S3\. Replace the highlighted text with the name of your bucket\. - -``` -version: 0.2 -phases: - install: - runtime-versions: - nodejs: 10 - build: - commands: - - npm install time - - export BUCKET=lambda-deployment-artifacts-123456789012 - - aws cloudformation package --template-file template.yml --s3-bucket $BUCKET --output-template-file outputtemplate.yml -artifacts: - type: zip - files: - - template.yml - - outputtemplate.yml -``` - -Commit and push the files to CodeCommit\. - -``` -~/lambda-pipeline-repo$ git add . -~/lambda-pipeline-repo$ git commit -m "project files" -~/lambda-pipeline-repo$ git push -``` - -## Create a pipeline - -Create a pipeline that deploys your application\. The pipeline monitors your repository for changes, runs an AWS CodeBuild build to create a deployment package, and deploys the application with AWS CloudFormation\. During the pipeline creation process, you also create the AWS CodeBuild build project\. - -**To create a pipeline** - -1. Open the [Developer tools console](https://console.aws.amazon.com/codesuite/home)\. - -1. Under **Pipeline**, choose **Pipelines**\. - -1. Choose **Create pipeline**\. - -1. Configure the pipeline settings and choose **Next**\. - + **Pipeline name** – **lambda\-pipeline** - + **Service role** – **New service role** - + **Artifact store** – **Default location** - -1. Configure source stage settings and choose **Next**\. - + **Source provider** – **AWS CodeCommit** - + **Repository name** – **lambda\-pipeline\-repo** - + **Branch name** – **master** - + **Change detection options** – **Amazon CloudWatch Events** - -1. For **Build provider**, choose **AWS CodeBuild**, and then choose **Create project**\. - -1. Configure build project settings and choose **Continue to CodePipeline**\. - + **Project name** – **lambda\-pipeline\-build** - + **Operating system** – **Ubuntu** - + **Runtime** – **Standard** - + **Runtime version** – **aws/codebuild/standard:2\.0** - + **Image version** – **Latest** - + **Buildspec name** – **buildspec\.yml** - -1. Choose **Next**\. - -1. Configure deploy stage settings and choose **Next**\. - + **Deploy provider** – **AWS CloudFormation** - + **Action mode** – **Create or replace a change set** - + **Stack name** – **lambda\-pipeline\-stack** - + **Change set name** – **lambda\-pipeline\-changeset** - + **Template** – **BuildArtifact::outputtemplate\.yml** - + **Capabilities** – **CAPABILITY\_IAM**, **CAPABILITY\_AUTO\_EXPAND** - + **Role name** – **cfn\-lambda\-pipeline** - -1. Choose **Create pipeline**\. - -The pipeline fails the first time it runs because it needs additional permissions\. In the next section, you add permissions to the role that's generated for your build stage\. - -## Update the build stage role - -During the build stage, AWS CodeBuild needs permission to upload the build output to your Amazon S3 bucket\. - -**To update the role** - -1. Open the [roles page](https://console.aws.amazon.com/iam/home#/roles) in the IAM console\. - -1. Choose **code\-build\-lamba\-pipeline\-service\-role**\. - -1. Choose **Attach policies**\. - -1. Attach **AmazonS3FullAccess**\. - -## Complete the deployment stage - -The deployment stage has an action that creates a change set for the AWS CloudFormation stack that manages your Lambda application\. A change set specifies the changes that are made to the stack, such as adding new resources and updating existing resources\. Change sets let you preview the changes that are made before making them, and add approval stages\. Add a second action that executes the change set to complete the deployment\. - -**To update the deployment stage** - -1. Open your pipeline in the [Developer tools console](https://console.aws.amazon.com/codesuite/home)\. - -1. Choose **Edit**\. - -1. Next to **Deploy**, choose **Edit stage**\. - -1. Choose **Add action group**\. - -1. Configure deploy stage settings and choose **Next**\. - + **Action name** – **execute\-changeset** - + **Action provider** – **AWS CloudFormation** - + **Input artifacts** – **BuildArtifact** - + **Action mode** – **Execute a change set** - + **Stack name** – **lambda\-pipeline\-stack** - + **Change set name** – **lambda\-pipeline\-changeset** - -1. Choose **Done**\. - -1. Choose **Save**\. - -1. Choose **Release change** to run the pipeline\. - -Your pipeline is ready\. Push changes to the master branch to trigger a deployment\. - -## Test the application - -The application includes an API Gateway API with a public endpoint that returns the current time\. Use the Lambda console to view the application and access the API\. - -**To test the application** - -1. Open the Lambda console [Applications page](https://console.aws.amazon.com/lambda/home#/applications)\. - -1. Choose **lambda\-pipeline\-stack**\. - -1. Under **Resources**, expand **ServerlessRestApi**\. - -1. Choose **Prod API endpoint**\. - -1. Add **/TimeResource** to the end of the URL\. For example, `https://l193nqxdjj.execute-api.us-east-2.amazonaws.com/Prod/TimeResource`\. - -1. Open the URL\. - -The API returns the current time in the following format\. - -``` -The time in Los Angeles is: Thu Jun 27 2019 16:07:20 GMT-0700 (PDT) -``` \ No newline at end of file diff --git a/doc_source/code-editor.md b/doc_source/code-editor.md deleted file mode 100644 index c3d782d9..00000000 --- a/doc_source/code-editor.md +++ /dev/null @@ -1,126 +0,0 @@ -# Creating functions using the AWS Lambda console editor - -The code editor in the AWS Lambda console enables you to write, test, and view the execution results of your Lambda function code\. - -The code editor includes the *menu bar*, *windows*, and the *editor pane*\. - -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/code-editor/code-editor.png) - -For a list of what the commands do, see the [Menu commands reference](https://docs.aws.amazon.com/cloud9/latest/user-guide/menu-commands.html) in the *AWS Cloud9 User Guide*\. Note that some of the commands listed in that reference are not available in the code editor\. - -**Topics** -+ [Working with files and folders](#code-editor-files) -+ [Working with code](#code-editor-code) -+ [Working in fullscreen mode](#code-editor-fullscreen) -+ [Working with preferences](#code-editor-prefs) - -## Working with files and folders - -You can use the **Environment** window in the code editor to create, open, and manage files for your function\. - -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/code-editor/code-editor-env.png) - -**To show or hide the Environment window**, choose the **Environment** button\. If the **Environment** button is not visible, choose **Window, Environment** on the menu bar\. - -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/code-editor/code-editor-env-button.png) - -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/code-editor/code-editor-env-menu.png) - -**To open a single file and show its contents in the editor pane**, double\-click the file in the **Environment** window\. - -**To open multiple files and show their contents in the editor pane**, choose the files in the **Environment** window\. Right\-click the selection, and then choose **Open**\. - -**To create a new file**, do one of the following: -+ In the **Environment** window, right\-click the folder where you want the new file to go, and then choose **New File**\. Type the file's name and extension, and then press Enter \. -+ Choose **File, New File** on the menu bar\. When you're ready to save the file, choose **File, Save** or **File, Save As** on the menu bar\. Then use the **Save As** dialog box that displays to name the file and choose where to save it\. -+ In the tab buttons bar in the editor pane, choose the **\+** button, and then choose **New File**\. When you're ready to save the file, choose **File, Save** or **File, Save As** on the menu bar\. Then use the **Save As** dialog box that displays to name the file and choose where to save it\. -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/code-editor/code-editor-env-new.png) - -**To create a new folder**, right\-click the folder in the **Environment** window where you want the new folder to go, and then choose **New Folder**\. Type the folder's name, and then press Enter \. - -**To save a file**, with the file open and its contents visible in the editor pane, choose **File, Save** on the menu bar\. - -**To rename a file or folder**, right\-click the file or folder in the **Environment** window\. Type the replacement name, and then press Enter \. - -**To delete files or folders**, choose the files or folders in the **Environment** window\. Right\-click the selection, and then choose **Delete**\. Then confirm the deletion by choosing **Yes** \(for a single selection\) or **Yes to All**\. - -**To cut, copy, paste, or duplicate files or folders**, choose the files or folders in the **Environment** window\. Right\-click the selection, and then choose **Cut**, **Copy**, **Paste**, or **Duplicate**, respectively\. - -**To collapse folders**, choose the gear icon in the **Environment** window, and then choose **Collapse All Folders**\. - -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/code-editor/code-editor-env-collapse.png) - -**To show or hide hidden files**, choose the gear icon in the **Environment** window, and then choose **Show Hidden Files**\. - -## Working with code - -Use the editor pane in the code editor to view and write code\. - -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/code-editor/code-editor-editor-pane.png) - -### Working with tab buttons - -Use the *tab buttons bar* to select, view, and create files\. - -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/code-editor/code-editor-tab-buttons-bar.png) - -**To display an open file's contents**, do one of the following: -+ Choose the file's tab\. -+ Choose the drop\-down menu button in the tab buttons bar, and then choose the file's name\. -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/code-editor/code-editor-drop-down-list.png) - -**To close an open file**, do one of the following: -+ Choose the **X** icon in the file's tab\. -+ Choose the file's tab\. Then choose the drop\-down menu button in the tab buttons bar, and choose **Close Pane**\. - -**To close multiple open files**, choose the drop\-down menu in the tab buttons bar, and then choose **Close All Tabs in All Panes** or **Close All But Current Tab** as needed\. - -**To create a new file**, choose the **\+** button in the tab buttons bar, and then choose **New File**\. When you're ready to save the file, choose **File, Save** or **File, Save As** on the menu bar\. Then use the **Save As** dialog box that displays to name the file and choose where to save it\. - -### Working with the status bar - -Use the status bar to move quickly to a line in the active file and to change how code is displayed\. - -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/code-editor/code-editor-status-bar.png) - -**To move quickly to a line in the active file**, choose the line selector, type the line number to go to, and then press Enter \. - -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/code-editor/code-editor-line-selector.png) - -**To change the code color scheme in the active file**, choose the code color scheme selector, and then choose the new code color scheme\. - -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/code-editor/code-editor-code-color.png) - -**To change in the active file whether soft tabs or spaces are used, the tab size, or whether to convert to spaces or tabs**, choose the spaces and tabs selector, and then choose the new settings\. - -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/code-editor/code-editor-spaces-tabs.png) - -**To change for all files whether to show or hide invisible characters or the gutter, auto\-pair brackets or quotes, wrap lines, or the font size**, choose the gear icon, and then choose the new settings\. - -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/code-editor/code-editor-status-bar-settings.png) - -## Working in fullscreen mode - -You can expand the code editor to get more room to work with your code\. - -To expand the code editor to the edges of the web browser window, choose the **Toggle fullscreen** button in the menu bar\. - -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/code-editor/code-editor-menu-bar-fullscreen.png) - -To shrink the code editor to its original size, choose the **Toggle fullscreen** button again\. - -In fullscreen mode, additional options are displayed on the menu bar: **Save** and **Test**\. Choosing **Save** saves the function code\. Choosing **Test** or **Configure Events** enables you to create or edit the function's test events\. - -## Working with preferences - -You can change various code editor settings such as which coding hints and warnings are displayed, code folding behaviors, code autocompletion behaviors, and much more\. - -To change code editor settings, choose the **Preferences** gear icon in the menu bar\. - -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/code-editor/code-editor-menu-bar-preferences.png) - -For a list of what the settings do, see the following references in the *AWS Cloud9 User Guide*\. -+ [Project setting changes you can make](https://docs.aws.amazon.com/cloud9/latest/user-guide/settings-project.html#settings-project-change) -+ [User setting changes you can make](https://docs.aws.amazon.com/cloud9/latest/user-guide/settings-user.html#settings-user-change) - -Note that some of the settings listed in those references are not available in the code editor\. \ No newline at end of file diff --git a/doc_source/configuration-aliases.md b/doc_source/configuration-aliases.md deleted file mode 100644 index 119b9238..00000000 --- a/doc_source/configuration-aliases.md +++ /dev/null @@ -1,124 +0,0 @@ -# AWS Lambda function aliases - -You can create one or more aliases for your AWS Lambda function\. A Lambda alias is like a pointer to a specific Lambda function version\. Users can access the function version using the alias ARN\. - -**To create an alias** - -1. Open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions)\. - -1. Choose a function\. - -1. In **Actions**, choose **Create alias**\. -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/version-actions.png) - -1. In the **Create a new alias** form, enter a name for the alias and an optional description\. Choose the function version for this alias\. - -To view the aliases that are currently defined for a function, choose **Qualifiers**, and choose the **Aliases** tab\. - -## Managing aliases with the Lambda API - -To create an alias, use the `create-alias` command\. - -``` -$ aws lambda create-alias --function-name my-function --name alias-name --function-version version-number --description " " -``` - -To change an alias to point a new version of the function, use the `update-alias` command\. - -``` -$ aws lambda update-alias --function-name my-function --name alias-name --function-version version-number -``` - - The AWS CLI commands in the preceding steps correspond to the following AWS Lambda APIs: -+ [CreateAlias](API_CreateAlias.md) -+ [UpdateAlias](API_UpdateAlias.md) - -## Using aliases - -Each alias has a unique ARN\. An alias can only point to a function version, not to another alias\. You can update an alias to point to a new version of the function\. - -Event sources such as Amazon S3 invoke your Lambda function\. These event sources maintain a mapping that identifies the function to invoke when events occur\. If you specify a Lambda function alias in the mapping configuration, you don't need to update the mapping when the function version changes\. - -In a resource policy, you can grant permissions for event sources to use your Lambda function\. If you specify an alias ARN in the policy, you don't need to update the policy when the function version changes\. - -## Resource policies - -When you use a [resource\-based policy](access-control-resource-based.md) to give a service, resource, or account access to your function, the scope of that permission depends on whether you applied it to an alias, to a version, or to the function\. If you use an alias name \(such as `helloworld:PROD`\), the permission is valid only for invoking the `helloworld` function using the alias ARN\. You get a permission error if you use a version ARN or the function ARN\. This includes the version ARN that the alias points to\. - -For example, the following AWS CLI command grants Amazon S3 permissions to invoke the PROD alias of the `helloworld` Lambda function\. Note that the `--qualifier` parameter specifies the alias name\. - -``` -$ aws lambda add-permission --function-name helloworld \ ---qualifier PROD --statement-id 1 --principal s3.amazonaws.com --action lambda:InvokeFunction \ ---source-arn arn:aws:s3:::examplebucket --source-account 123456789012 -``` - -In this case, Amazon S3 is now able to invoke the PROD alias\. Lambda can then execute the `helloworld` Lambda function version that the PROD alias references\. For this to work correctly, you must use the PROD alias ARN in the S3 bucket's notification configuration\. - -## Alias routing configuration - -Use routing configuration on an alias to send a portion of traffic to a second function version\. For example, you can reduce the risk of deploying a new version by configuring the alias to send most of the traffic to the existing version, and only a small percentage of traffic to the new version\. - -You can point an alias to a maximum of two Lambda function versions\. The versions must meet the following criteria: -+ Both versions must have the same IAM execution role\. -+ Both versions must have the same [dead\-letter queue](https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html#dlq) configuration, or no dead\-letter queue configuration\. -+ Both versions must be published\. The alias cannot point to `$LATEST`\. - -**To configure routing on an alias** - -1. Open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions)\. - -1. Choose a function\. - -1. Verify that the function has at least two published versions\. To do this, choose **Qualifiers** and then choose **Versions** to display the list of versions\. If you need to create additional versions, follow the instructions in [AWS Lambda function versions](configuration-versions.md)\. - -1. On the **Actions** menu, choose **Create alias**\. - -1. In the **Create a new alias** window, enter a value for **Name**, optionally enter a value for **Description**, and choose the **Version** of the Lambda function that the alias references\. - -1. Under **Additional version**, specify the following items: - - 1. Choose the second Lambda function version\. - - 1. Enter a weight value for the function\. *Weight* is the percentage of traffic that is assigned to that version when the alias is invoked\. The first version receives the residual weight\. For example, if you specify 10 percent to **Additional version**, the first version is assigned 90 percent automatically\. - -1. Choose **Create**\. - -### Configuring alias routing - -Use the `create-alias` and `update-alias` commands to configure the traffic weights between two function versions\. When you create or update the alias, you specify the traffic weight in the `routing-config` parameter\. - -The following example creates an alias \(named **routing\-alias**\) for a Lambda function\. The alias points to version 1 of the function\. Version 2 of the function receives 3 percent of the traffic\. The remaining 97 percent of traffic is routed to version 1\. - -``` -$ aws lambda create-alias --name routing-alias --function-name my-function --function-version 1 \ ---routing-config AdditionalVersionWeights={"2"=0.03} -``` - -Use the `update-alias` command to increase the percentage of incoming traffic to version 2\. In the following example, you increase the traffic to 5 percent\. - -``` -$ aws lambda update-alias --name routing-alias --function-name my-function \ ---routing-config AdditionalVersionWeights={"2"=0.05} -``` - -To route all traffic to version 2, use the `UpdateAlias` command to change the `function-version` property to point the alias to version 2\. The command also resets the routing configuration\. - -``` -$ aws lambda update-alias --name routing-alias --function-name my-function \ ---function-version 2 --routing-config AdditionalVersionWeights={} -``` - - The CLI commands in the preceding steps correspond to the following AWS Lambda API operations: -+ [CreateAlias](API_CreateAlias.md) -+ [UpdateAlias](API_UpdateAlias.md) - -### Determining which version has been invoked - -When you configure traffic weights between two function versions, there are two ways to determine the Lambda function version that has been invoked: -+ **CloudWatch Logs** – Lambda automatically emits a `START` log entry that contains the invoked version ID to CloudWatch Logs for every function invocation\. The following is an example: - - `19:44:37 START RequestId: request id Version: $version ` - - For alias invocations, Lambda uses the `Executed Version` dimension to filter the metric data by the executed version\. For more information, see [Working with AWS Lambda function metrics](monitoring-metrics.md)\. -+ **Response payload \(synchronous invocations\)** – Responses to synchronous function invocations include an `x-amz-executed-version` header to indicate which function version has been invoked\. \ No newline at end of file diff --git a/doc_source/configuration-concurrency.md b/doc_source/configuration-concurrency.md deleted file mode 100644 index a0a696df..00000000 --- a/doc_source/configuration-concurrency.md +++ /dev/null @@ -1,206 +0,0 @@ -# Managing concurrency for a Lambda function - -Concurrency is the number of requests that your function is serving at any given time\. When your function is invoked, Lambda allocates an instance of it to process the event\. When the function code finishes running, it can handle another request\. If the function is invoked again while a request is still being processed, another instance is allocated, which increases the function's concurrency\. - -Concurrency is subject to a Regional [limit](gettingstarted-limits.md) that is shared by all functions in a Region\. To ensure that a function can always reach a certain level of concurrency, you can configure the function with [reserved concurrency](#configuration-concurrency-reserved)\. When a function has reserved concurrency, no other function can use that concurrency\. Reserved concurrency also limits the maximum concurrency for the function, and applies to the function as a whole, including versions and aliases\. - -When Lambda allocates an instance of your function, the [runtime](lambda-runtimes.md) loads your function's code and runs initialization code that you define outside of the handler\. If your code and dependencies are large, or you create SDK clients during initialization, this process can take some time\. As your function [scales up](invocation-scaling.md), this causes the portion of requests that are served by new instances to have higher latency than the rest\. - -To enable your function to scale without fluctuations in latency, use [provisioned concurrency](#configuration-concurrency-provisioned)\. By allocating provisioned concurrency before an increase in invocations, you can ensure that all requests are served by initialized instances with very low latency\. You can configure provisioned concurrency on a version of a function, or on an alias\. - -Lambda also integrates with [Application Auto Scaling](https://docs.aws.amazon.com/autoscaling/application/userguide/)\. You can configure Application Auto Scaling to manage provisioned concurrency on a schedule or based on utilization\. Use scheduled scaling to increase provisioned concurrency in anticipation of peak traffic\. To increase provisioned concurrency automatically as needed, use [the Application Auto Scaling API](#configuration-concurrency-api) to register a target and create a scaling policy\. - -Provisioned concurrency counts towards a function's reserved concurrency and Regional limits\. If the amount of provisioned concurrency on a function's versions and aliases adds up to the function's reserved concurrency, all invocations run on provisioned concurrency\. This configuration also has the effect of throttling the unpublished version of the function \(`$LATEST`\), which prevents it from executing\. - -**Topics** -+ [Configuring reserved concurrency](#configuration-concurrency-reserved) -+ [Configuring provisioned concurrency](#configuration-concurrency-provisioned) -+ [Configuring concurrency with the Lambda API](#configuration-concurrency-api) - -## Configuring reserved concurrency - -To manage reserved concurrency settings for a function, use the Lambda console\. - -**To reserve concurrency for a function** - -1. Open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions)\. - -1. Choose a function\. - -1. Under **Concurrency**, choose **Reserve concurrency**\. - -1. Enter the amount of concurrency to reserve for the function\. - -1. Choose **Save**\. - -You can reserve up to the **Unreserved account concurrency** value that is shown, minus 100 for functions that don't have reserved concurrency\. To throttle a function, set the reserved concurrency to zero\. This stops any events from being processed until you remove the limit\. - -The following example shows two functions with pools of reserved concurrency, and the unreserved concurrency pool used by other functions\. Throttling errors occur when all of the concurrency in a pool is in use\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-concurrency-reserved.png) - -**Legend** -+ ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-concurrency.concurrency.png) Function concurrency -+ ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-concurrency.reserved.png) Reserved concurrency -+ ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-concurrency.unreserved.png) Unreserved concurrency -+ ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-concurrency.throttling.png) Throttling - -Reserving concurrency has the following effects\. -+ **Other functions can't prevent your function from scaling** – All of your account's functions in the same Region without reserved concurrency share the pool of unreserved concurrency\. Without reserved concurrency, other functions can use up all of the available concurrency\. This prevents your function from scaling up when needed\. -+ **Your function can't scale out of control** – Reserved concurrency also limits your function from using concurrency from the unreserved pool, which caps its maximum concurrency\. You can reserve concurrency to prevent your function from using all the available concurrency in the Region, or from overloading downstream resources\. - -Setting per\-function concurrency can impact the concurrency pool that is available to other functions\. To avoid issues, limit the number of users who can use the `PutFunctionConcurrency` and `DeleteFunctionConcurrency` API operations\. - -## Configuring provisioned concurrency - -To manage provisioned concurrency settings for a version or alias, use the Lambda console\. - -**To reserve concurrency for an alias** - -1. Open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions)\. - -1. Choose a function\. - -1. Under **Provisioned concurrency configurations**, choose **Add**\. - -1. Choose an alias or version\. - -1. Enter the amount of provisioned concurrency to allocate\. - -1. Choose **Save**\. - -You can manage provisioned concurrency for all aliases and versions from the function configuration page\. The list of provisioned concurrency configurations shows the allocation progress of each configuration\. Provisioned concurrency settings are also available on the configuration page for each version and alias\. - -In the following example, the `my-function-DEV` and `my-function-PROD` functions are configured with both reserved and provisioned concurrency\. For `my-function-DEV`, the full pool of reserved concurrency is also provisioned concurrency\. In this case, all invocations either run on provisioned concurrency or are throttled\. For `my-function-PROD`, a portion of the reserved concurrency pool is standard concurrency\. When all provisioned concurrency is in use, the function scales on standard concurrency to serve any additional requests\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-concurrency-provisioned.png) - -**Legend** -+ ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-concurrency.concurrency.png) Function concurrency -+ ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-concurrency.reserved.png) Reserved concurrency -+ ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-concurrency.provisioned.png) Provisioned concurrency -+ ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-concurrency.unreserved.png) Unreserved concurrency -+ ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-concurrency.throttling.png) Throttling - -Provisioned concurrency does not come online immediately after you configure it\. Lambda starts allocating provisioned concurrency after a minute or two of preparation\. Similar to how functions [scale under load](invocation-scaling.md), up to 3000 instances of the function can be initialized at once, depending on the Region\. After the initial burst, instances are allocated at a steady rate of 500 per minute until the request is fulfilled\. When you request provisioned concurrency for multiple functions or versions of a function in the same Region, scaling limits apply across all requests\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-scaling-provisioned.png) - -**Legend** -+ ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-scaling-provisioned.instances.png) Function instances -+ ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-scaling-provisioned.open.png) Open requests -+ ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-scaling-provisioned.provisioned.png) Provisioned concurrency -+ ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-scaling-provisioned.standard.png) Standard concurrency - -Your function's [initialization code](gettingstarted-features.md#gettingstarted-features-programmingmodel) runs during allocation and every few hours, as running instances of your function are recycled\. You can see the initialization time in logs and [traces](lambda-x-ray.md) after an instance processes a request\. However, initialization is billed even if the instance never processes a request\. Provisioned concurrency runs continually and is billed separately from initialization and invocation costs\. For details, see [AWS Lambda pricing](https://aws.amazon.com/lambda/pricing/)\. - -Each version of a function can only have one provisioned concurrency configuration\. This can be directly on the version itself, or on an alias that points to the version\. Two aliases can't allocate provisioned concurrency for the same version\. Also, you can't allocate provisioned concurrency on an alias that points to the unpublished version \(`$LATEST`\)\. - -When you change the version that an alias points to, provisioned concurrency is deallocated from the old version and then allocated to the new version\. You can add a routing configuration to an alias that has provisioned concurrency\. However, you can't manage provisioned concurrency settings on the alias while the routing configuration is in place\. - -Lambda emits the following metrics for provisioned concurrency: - -**Provisioned concurrency metrics** -+ `ProvisionedConcurrentExecutions` -+ `ProvisionedConcurrencyInvocations` -+ `ProvisionedConcurrencySpilloverInvocations` -+ `ProvisionedConcurrencyUtilization` - -For details, see [Working with AWS Lambda function metrics](monitoring-metrics.md)\. - -## Configuring concurrency with the Lambda API - -To manage concurrency settings and autoscaling with the AWS CLI or AWS SDK, use the following API operations\. -+ [PutFunctionConcurrency](API_PutFunctionConcurrency.md) -+ [GetFunctionConcurrency](https://docs.aws.amazon.com/lambda/latest/dg/API_GetFunctionConcurrency.html) -+ [DeleteFunctionConcurrency](API_DeleteFunctionConcurrency.md) -+ [PutProvisionedConcurrencyConfig](https://docs.aws.amazon.com/lambda/latest/dg/API_PutProvisionedConcurrencyConfig.html) -+ [GetProvisionedConcurrencyConfig](https://docs.aws.amazon.com/lambda/latest/dg/API_GetProvisionedConcurrencyConfig.html) -+ [ListProvisionedConcurrencyConfigs](https://docs.aws.amazon.com/lambda/latest/dg/API_ListProvisionedConcurrencyConfigs.html) -+ [DeleteProvisionedConcurrencyConfig](https://docs.aws.amazon.com/lambda/latest/dg/API_DeleteProvisionedConcurrencyConfig.html) -+ [GetAccountSettings](API_GetAccountSettings.md) -+ \(Application Auto Scaling\) [RegisterScalableTarget](https://docs.aws.amazon.com/autoscaling/application/APIReference/API_RegisterScalableTarget.html) -+ \(Application Auto Scaling\) [PutScalingPolicy](https://docs.aws.amazon.com/autoscaling/application/APIReference/API_PutScalingPolicy.html) - -To configure reserved concurrency with the AWS CLI, use the `put-function-concurrency` command\. The following command reserves a concurrency of 100 for a function named `my-function`: - -``` -$ aws lambda put-function-concurrency --function-name my-function --reserved-concurrent-executions 100 -{ - "ReservedConcurrentExecutions": 100 -} -``` - -To allocate provisioned concurrency for a function, use `put-provisioned-concurrency-config`\. The following command allocates a concurrency of 100 for the `BLUE` alias of a function named `my-function`: - -``` -$ aws lambda put-provisioned-concurrency-config --function-name my-function \ ---qualifier BLUE --provisioned-concurrent-executions 100 -{ - "Requested ProvisionedConcurrentExecutions": 100, - "Allocated ProvisionedConcurrentExecutions": 0, - "Status": "IN_PROGRESS", - "LastModified": "2019-11-21T19:32:12+0000" -} -``` - -To configure Application Auto Scaling to manage provisioned concurrency, use the Application Auto Scaling to configure [target tracking scaling](https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-target-tracking.html)\. First, register a function's alias as a scaling target\. The following example registers the `BLUE` alias of a function named `my-function`: - -``` -$ aws application-autoscaling register-scalable-target --service-namespace lambda \ - --resource-id function:my-function:BLUE --min-capacity 1 --max-capacity 100 \ - --scalable-dimension lambda:function:ProvisionedConcurrency -``` - -Next, apply a scaling policy to the target\. The following example configures Application Auto Scaling to adjust the provisioned concurrency configuration for an alias to keep utilization near 70 percent: - -``` -$ aws application-autoscaling put-scaling-policy --service-namespace lambda \ ---scalable-dimension lambda:function:ProvisionedConcurrency --resource-id function:my-function:BLUE \ ---policy-name my-policy --policy-type TargetTrackingScaling \ ---target-tracking-scaling-policy-configuration '{ "TargetValue": 0.7, "PredefinedMetricSpecification": { "PredefinedMetricType": "LambdaProvisionedConcurrencyUtilization" }}' -{ - "PolicyARN": "arn:aws:autoscaling:us-east-2:123456789012:scalingPolicy:12266dbb-1524-xmpl-a64e-9a0a34b996fa:resource/lambda/function:my-function:BLUE:policyName/my-policy", - "Alarms": [ - { - "AlarmName": "TargetTracking-function:my-function:BLUE-AlarmHigh-aed0e274-xmpl-40fe-8cba-2e78f000c0a7", - "AlarmARN": "arn:aws:cloudwatch:us-east-2:123456789012:alarm:TargetTracking-function:my-function:BLUE-AlarmHigh-aed0e274-xmpl-40fe-8cba-2e78f000c0a7" - }, - { - "AlarmName": "TargetTracking-function:my-function:BLUE-AlarmLow-7e1a928e-xmpl-4d2b-8c01-782321bc6f66", - "AlarmARN": "arn:aws:cloudwatch:us-east-2:123456789012:alarm:TargetTracking-function:my-function:BLUE-AlarmLow-7e1a928e-xmpl-4d2b-8c01-782321bc6f66" - } - ] -} -``` - -Application Auto Scaling creates two alarms in CloudWatch\. The first alarm triggers when the utilization of provisioned concurrency consistently exceeds 70 percent\. When this happens, Application Auto Scaling allocates more provisioned concurrency to reduce utilization\. The second alarm triggers when utilization is consistently less than 63 percent \(90 percent of the 70 percent target\)\. When this happens, Application Auto Scaling reduces the alias's provisioned concurrency\. - -In the following example, a function scales between a minimum and maximum amount of provisioned concurrency based on utilization\. When the number of open requests increases, Application Auto Scaling increases provisioned concurrency in large steps until it reaches the configured maximum\. The function continues to scale on standard concurrency until utilization starts to drop\. When utilization is consistently low, Application Auto Scaling decreases provisioned concurrency in smaller periodic steps\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-scaling-provisioned-auto.png) - -**Legend** -+ ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-scaling-provisioned.instances.png) Function instances -+ ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-scaling-provisioned.open.png) Open requests -+ ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-scaling-provisioned.provisioned.png) Provisioned concurrency -+ ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-scaling-provisioned.standard.png) Standard concurrency - -To view your account's concurrency limits in a Region, use `get-account-settings`\. - -``` -$ aws lambda get-account-settings -{ - "AccountLimit": { - "TotalCodeSize": 80530636800, - "CodeSizeUnzipped": 262144000, - "CodeSizeZipped": 52428800, - "ConcurrentExecutions": 1000, - "UnreservedConcurrentExecutions": 900 - }, - "AccountUsage": { - "TotalCodeSize": 174913095, - "FunctionCount": 52 - } -} -``` \ No newline at end of file diff --git a/doc_source/configuration-console.md b/doc_source/configuration-console.md deleted file mode 100644 index c4edb96b..00000000 --- a/doc_source/configuration-console.md +++ /dev/null @@ -1,58 +0,0 @@ -# Configuring functions in the AWS Lambda console - -You can use the Lambda console to configure function settings, add triggers and destinations, and update and test your code\. - -To manage a function, open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions) and choose a function\. The function designer is at the top of the configuration page\. - -![\[The function designer in the AWS Lambda console.\]](http://docs.aws.amazon.com/lambda/latest/dg/images/console-designer.png) - -The designer shows an overview of your function and its upstream and downstream resources\. You can use it to configure triggers, layers, and destinations\. -+ **Triggers** – Triggers are services and resources that you have configured to invoke your function\. Choose **Add trigger** to create a Lambda [event source mapping](invocation-eventsourcemapping.md) or to configure a trigger in another service that the Lambda console integrates with\. For details about these services and others, see [Using AWS Lambda with other services](lambda-services.md)\. -+ **Layers** – Choose the **Layers** node to add [layers](configuration-layers.md) to your application\. A layer is a ZIP archive that contains libraries, a custom runtime, or other dependencies\. -+ **Destinations** – Add a destination to your function to send details about invocation results to another service\. You can send invocation records when your function is invoked [asynchronously](invocation-async.md), or by an [event source mapping](invocation-eventsourcemapping.md) that reads from a stream\. - -With the function node selected in the designer, you can modify the following settings\. - -**Function settings** -+ **Code** – The code and dependencies of your function\. For scripting languages, you can edit your function code in the embedded [editor](code-editor.md)\. To add libraries, or for languages that the editor doesn't support, upload a [deployment package](gettingstarted-features.md#gettingstarted-features-package)\. If your deployment package is larger than 50 MB, choose **Upload a file from Amazon S3**\. -+ **Runtime** – The [Lambda runtime](lambda-runtimes.md) that executes your function\. -+ **Handler** – The method that the runtime executes when your function is invoked, such as `index.handler`\. The first value is the name of the file or module\. The second value is the name of the method\. -+ **Environment variables** – Key\-value pairs that Lambda sets in the execution environment\. [ Use environment variables](configuration-envvars.md) to extend your function's configuration outside of code\. -+ **Tags** – Key\-value pairs that Lambda attaches to your function resource\. [Use tags](configuration-tags.md) to organize Lambda functions into groups for cost reporting and filtering in the Lambda console\. - - Tags apply to the entire function, including all versions and aliases\. -+ **Execution role** – The [IAM role](lambda-intro-execution-role.md) that AWS Lambda assumes when it executes your function\. -+ **Description** – A description of the function\. -+ **Memory**– The amount of memory available to the function during execution\. Choose an amount [between 128 MB and 3,008 MB](gettingstarted-limits.md) in 64\-MB increments\. - - Lambda allocates CPU power linearly in proportion to the amount of memory configured\. At 1,792 MB, a function has the equivalent of one full vCPU \(one vCPU\-second of credits per second\)\. -+ **Timeout** – The amount of time that Lambda allows a function to run before stopping it\. The default is 3 seconds\. The maximum allowed value is 900 seconds\. -+ **Virtual private cloud \(VPC\)** – If your function needs network access to resources that are not available over the internet, [configure it to connect to a VPC](configuration-vpc.md)\. -+ **Database proxies** – [Create a database proxy](configuration-database.md) for functions that use an Amazon RDS DB instance or cluster\. -+ **Active tracing** – Sample incoming requests and [trace sampled requests with AWS X\-Ray](lambda-x-ray.md)\. -+ **Concurrency** – [Reserve concurrency for a function](configuration-concurrency.md) to set the maximum number of simultaneous executions for a function\. Provision concurrency to ensure that a function can scale without fluctuations in latency\. - - Reserved concurrency applies to the entire function, including all versions and aliases\. -+ **Asynchronous invocation** – [Configure error handling behavior](invocation-async.md) to reduce the number of retries that Lambda attempts, or the amount of time that unprocessed events stay queued before Lambda discards them\. [Configure a dead\-letter queue](invocation-async.md#dlq) to retain discarded events\. - - You can configure error handling settings on a function, version, or alias\. - -Except as noted in the preceding list, you can only change function settings on the unpublished version of a function\. When you publish a version, code and most settings are locked to ensure a consistent experience for users of that version\. Use [aliases](configuration-aliases.md) to propagate configuration changes in a controlled manner\. - -To configure functions with the Lambda API, use the following actions: -+ [UpdateFunctionCode](API_UpdateFunctionCode.md) – Update the function's code\. -+ [UpdateFunctionConfiguration](API_UpdateFunctionConfiguration.md) – Update version\-specific settings\. -+ [TagResource](API_TagResource.md) – Tag a function\. -+ [AddPermission](API_AddPermission.md) – Modify the [resource\-based policy](access-control-resource-based.md) of a function, version, or alias\. -+ [PutFunctionConcurrency](API_PutFunctionConcurrency.md) – Configure a function's reserved concurrency\. -+ [PublishVersion](API_PublishVersion.md) – Create an immutable version with the current code and configuration\. -+ [CreateAlias](API_CreateAlias.md) – Create aliases for function versions\. -+ [PutFunctionEventInvokeConfig](https://docs.aws.amazon.com/lambda/latest/dg/API_PutFunctionEventInvokeConfig.html) – Configure error handling for asynchronous invocation\. - -For example, to update a function's memory setting with the AWS CLI, use the `update-function-configuration` command\. - -``` -$ aws lambda update-function-configuration --function-name my-function --memory-size 256 -``` - -For function configuration best practices, see [Function Configuration](best-practices.md#function-configuration)\. \ No newline at end of file diff --git a/doc_source/configuration-database.md b/doc_source/configuration-database.md deleted file mode 100644 index 2080ab30..00000000 --- a/doc_source/configuration-database.md +++ /dev/null @@ -1,43 +0,0 @@ -# Configuring database access for a Lambda function - -You can use the Lambda console to create an Amazon RDS Proxy database proxy for your function\. A database proxy manages a pool of database connections and relays queries from a function\. This enables a function to reach high [concurrency](gettingstarted-concepts.md#gettingstarted-concepts-concurrency) levels without exhausting database connections\. - -**To create a database proxy** - -1. Open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions)\. - -1. Choose a function\. - -1. Choose **Add database proxy**\. - -1. Configure the following options\. - + **Proxy identifier** – The name of the proxy\. - + **RDS DB instance** – A MySQL 5\.6 or MySQL 5\.7 DB instance or cluster\. - + **Secret** – A Secrets Manager secret with the database user name and password\. -**Example Secret** - - ``` - { - "username": "admin", - "password": "e2abcecxmpldc897" - } - ``` - + **IAM role** – An IAM role with permission to use the secret, and a trust policy that allows Amazon RDS to assume the role\. - -1. Choose **Add**\. - -Proxy creation takes a few minutes\. When the proxy is available, configure your function to connect to the proxy endpoint instead of the database endpoint\. - -Standard [Amazon RDS Proxy pricing](https://aws.amazon.com/rds/proxy/pricing/) applies\. For more information, see [Managing connections with the Amazon RDS Proxy](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/rds-proxy.html) in the Amazon Aurora User Guide\. - -## Sample application - -Sample applications that demonstrate the use of Lambda with an Amazon RDS database are available in this guide's GitHub repository\. There are two applications: -+ [RDS MySQL](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/rds-mysql) – The AWS CloudFormation template `template-vpcrds.yml` creates a MySQL 5\.7 database in a private VPC\. In the sample application, a Lambda function proxies queries to the database\. The function and database templates both use Secrets Manager to access database credentials\. - - [ ![\[The dbadmin function relays queries to a database.\]](http://docs.aws.amazon.com/lambda/latest/dg/images/sample-rdsmysql.png)](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/rds-mysql) -+ [List Manager](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/list-manager) – A processor function reads events from a Kinesis stream\. It uses the data from the events to update DynamoDB tables, and stores a copy of the event in a MySQL database\. - - [ ![\[The processor function processes Kinesis events and stores the events in a MySQL database.\]](http://docs.aws.amazon.com/lambda/latest/dg/images/sample-listmanager.png)](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/list-manager) - -To use the sample applications, follow the instructions in the GitHub repository: [RDS MySQL](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/rds-mysql/README.md), [List Manager](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/list-manager/README.md)\. \ No newline at end of file diff --git a/doc_source/configuration-envvars.md b/doc_source/configuration-envvars.md deleted file mode 100644 index 3620c86a..00000000 --- a/doc_source/configuration-envvars.md +++ /dev/null @@ -1,251 +0,0 @@ -# Using AWS Lambda environment variables - -You can use environment variables to store secrets securely and adjust your function's behavior without updating code\. An environment variable is a pair of strings that are stored in a function's version\-specific configuration\. The Lambda runtime makes environment variables available to your code and sets additional environment variables that contain information about the function and invocation request\. - -You set environment variables on the unpublished version of your function by specifying a key and value\. When you publish a version, the environment variables are locked for that version along with other [version\-specific configuration](configuration-console.md)\. - -**To set environment variables in the Lambda console** - -1. Open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions)\. - -1. Choose a function\. - -1. Under **Environment variables**, choose **Edit**\. - -1. Choose **Add environment variable**\. - -1. Enter a key and value\. - -**Requirements** - + Keys start with a letter and are at least two characters\. - + Keys only contain letters, numbers, and the underscore character \(`_`\)\. - + Keys aren't [reserved by Lambda](#configuration-envvars-runtime)\. - + The total size of all environment variables doesn't exceed 4 KB\. - -1. Choose **Save**\. - -Use environment variables to pass environment\-specific settings to your code\. For example, you can have two functions with the same code but different configuration\. One function connects to a test database, and the other connects to a production database\. In this situation, you use environment variables to tell the function the hostname and other connection details for the database\. You might also set an environment variable to configure your test environment to use more verbose logging or more detailed tracing\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/console-env.png) - -To retrieve environment variables in your function code, use the standard method for your programming language\. - ------- -#### [ Node\.js ] - -``` -let region = process.env.AWS_REGION -``` - ------- -#### [ Python ] - -``` -import os -region = os.environ['AWS_REGION'] -``` - ------- -#### [ Ruby ] - -``` -region = ENV["AWS_REGION"] -``` - ------- -#### [ Java ] - -``` -String region = System.getenv("AWS_REGION"); -``` - ------- -#### [ Go ] - -``` -var region = os.Getenv("AWS_REGION") -``` - ------- -#### [ C\# ] - -``` -string region = Environment.GetEnvironmentVariable("AWS_REGION"); -``` - ------- -#### [ PowerShell ] - -``` -$region = $env:AWS_REGION -``` - ------- - -Lambda stores environment variables securely by encrypting them at rest\. You can [configure Lambda to use a different encryption key](#configuration-envvars-encryption), encrypt environment variable values on the client side, or set environment variables in an AWS CloudFormation template with AWS Secrets Manager\. - -**Topics** -+ [Runtime environment variables](#configuration-envvars-runtime) -+ [Securing environment variables](#configuration-envvars-encryption) -+ [Configuring environment variables with the Lambda API](#configuration-envvars-api) -+ [Sample code and templates](#configuration-envvars-samples) - -## Runtime environment variables - -Lambda [runtimes](lambda-runtimes.md) set several environment variables during initialization\. Most of the environment variables provide information about the function or runtime\. The keys for these environment variables are *reserved* and cannot be set in your function configuration\. - -**Reserved environment variables** -+ `_HANDLER` – The handler location configured on the function\. -+ `AWS_REGION` – The AWS Region where the Lambda function is executed\. -+ `AWS_EXECUTION_ENV` – The [runtime identifier](lambda-runtimes.md), prefixed by `AWS_Lambda_`—for example, `AWS_Lambda_java8`\. -+ `AWS_LAMBDA_FUNCTION_NAME` – The name of the function\. -+ `AWS_LAMBDA_FUNCTION_MEMORY_SIZE` – The amount of memory available to the function in MB\. -+ `AWS_LAMBDA_FUNCTION_VERSION` – The version of the function being executed\. -+ `AWS_LAMBDA_LOG_GROUP_NAME`, `AWS_LAMBDA_LOG_STREAM_NAME` – The name of the Amazon CloudWatch Logs group and stream for the function\. -+ `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN` – The access keys obtained from the function's [execution role](lambda-intro-execution-role.md)\. -+ `AWS_LAMBDA_RUNTIME_API` – \([Custom runtime](runtimes-custom.md)\) The host and port of the [runtime API](runtimes-api.md)\. -+ `LAMBDA_TASK_ROOT` – The path to your Lambda function code\. -+ `LAMBDA_RUNTIME_DIR` – The path to runtime libraries\. -+ `TZ` – The environment's time zone \(`UTC`\)\. The execution environment uses NTP to synchronize the system clock\. - -The following additional environment variables aren't reserved and can be extended in your function configuration\. - -**Unreserved environment variables** -+ `LANG` – The locale of the runtime \(`en_US.UTF-8`\)\. -+ `PATH` – The execution path \(`/usr/local/bin:/usr/bin/:/bin:/opt/bin`\)\. -+ `LD_LIBRARY_PATH` – The system library path \(`/lib64:/usr/lib64:$LAMBDA_RUNTIME_DIR:$LAMBDA_RUNTIME_DIR/lib:$LAMBDA_TASK_ROOT:$LAMBDA_TASK_ROOT/lib:/opt/lib`\)\. -+ `NODE_PATH` – \([Node\.js](lambda-nodejs.md)\) The Node\.js library path \(`/opt/nodejs/node12/node_modules/:/opt/nodejs/node_modules:$LAMBDA_RUNTIME_DIR/node_modules`\)\. -+ `PYTHONPATH` – \([Python 2\.7, 3\.6, 3\.8](lambda-python.md)\) The Python library path \(`$LAMBDA_RUNTIME_DIR`\)\. -+ `GEM_PATH` – \([Ruby](lambda-ruby.md)\) The Ruby library path \(`$LAMBDA_TASK_ROOT/vendor/bundle/ruby/2.5.0:/opt/ruby/gems/2.5.0`\)\. - -The sample values shown reflect the latest runtimes\. The presence of specific variables or their values can vary on earlier runtimes\. - -## Securing environment variables - -Lambda encrypts environment variables with a key that it creates in your account \(an AWS managed customer master key \(CMK\)\)\. Use of this key is free\. You can also choose to provide your own key for Lambda to use instead of the default key\. - -When you provide the key, only users in your account with access to the key can view or manage environment variables on the function\. Your organization might also have internal or external requirements to manage keys that are used for encryption and to control when they're rotated\. - -**To use a customer managed CMK** - -1. Open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions)\. - -1. Choose a function\. - -1. Under **Environment variables**, choose **Edit**\. - -1. Expand **Encryption configuration**\. - -1. Choose **Use a customer master key**\. - -1. Choose your customer managed CMK\. - -1. Choose **Save**\. - -Customer managed CMKs incur standard [AWS KMS charges](https://aws.amazon.com/kms/pricing/)\. - -No AWS KMS permissions are required for your user or the function's execution role to use the default encryption key\. To use a customer managed CMK, you need permission to use the key\. Lambda uses your permissions to create a grant on the key\. This allows Lambda to use it for encryption\. -+ `kms:ListAliases` – To view keys in the Lambda console\. -+ `kms:CreateGrant`, `kms:Encrypt` – To configure a customer managed CMK on a function\. -+ `kms:Decrypt` – To view and manage environment variables that are encrypted with a customer managed CMK\. - -You can get these permissions from your user account or from a key's resource\-based permissions policy\. `ListAliases` is provided by the [managed policies for Lambda](access-control-identity-based.md)\. Key policies grant the remaining permissions to users in the **Key users** group\. - -Users without `Decrypt` permissions can still manage functions, but they can't view environment variables or manage them in the Lambda console\. To prevent a user from viewing environment variables, add a statement to the user's permissions that denies access to the default key, a customer managed key, or all keys\. - -**Example IAM policy – Deny access by key ARN** - -``` -{ - "Version": "2012-10-17", - "Statement": [ - { - "Sid": "VisualEditor0", - "Effect": "Deny", - "Action": [ - "kms:Decrypt" - ], - "Resource": "arn:aws:kms:us-east-2:123456789012:key/3be10e2d-xmpl-4be4-bc9d-0405a71945cc" - } - ] -} -``` - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/env-accessdenied.png) - -For details on managing key permissions, see [Using key policies in AWS KMS](https://docs.aws.amazon.com/kms/latest/developerguide/key-policies.html)\. - -You can also encrypt environment variable values on the client side before sending them to Lambda, and decrypt them in your function code\. This obscures secret values in the Lambda console and API output, even for users who have permission to use the key\. In your code, you retrieve the encrypted value from the environment and decrypt it by using the AWS KMS API\. - -**To encrypt environment variables on the client side** - -1. Open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions)\. - -1. Choose a function\. - -1. Under **Environment variables**, choose **Edit**\. - -1. Expand **Encryption configuration**\. - -1. Choose **Enable helpers for encryption in transit**\. - -1. Choose **Encrypt** next to a variable to encrypt its value\. - -1. Choose **Save**\. - -To view sample code for your function's language, choose **Code** next to an environment variable\. The sample code shows how to retrieve an environment variable in a function and decrypt its value\. - -Another option is to store passwords in AWS Secrets Manager secrets\. You can reference the secret in your AWS CloudFormation templates to set passwords on databases\. You can also set the value of an environment variable on the Lambda function\. For an example, see the next section\. - -## Configuring environment variables with the Lambda API - -To manage environment variables with the AWS CLI or AWS SDK, use the following API operations\. -+ [UpdateFunctionConfiguration](API_UpdateFunctionConfiguration.md) -+ [GetFunctionConfiguration](API_GetFunctionConfiguration.md) -+ [CreateFunction](API_CreateFunction.md) - -The following example sets two environment variables on a function named `my-function`\. - -``` -$ aws lambda update-function-configuration --function-name my-function \ - --environment "Variables={BUCKET=my-bucket,KEY=file.txt}" -``` - -When you apply environment variables with the `update-function-configuration` command, the entire contents of the `Variables` structure is replaced\. To retain existing environment variables when you add a new one, include all existing values in your request\. - -To get the current configuration, use the `get-function-configuration` command\. - -``` -$ aws lambda get-function-configuration --function-name my-function -{ - "FunctionName": "my-function", - "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function", - "Runtime": "nodejs12.x", - "Role": "arn:aws:iam::123456789012:role/lambda-role", - "Environment": { - "Variables": { - "BUCKET": "my-bucket", - "KEY": "file.txt" - } - }, - "RevisionId": "0894d3c1-2a3d-4d48-bf7f-abade99f3c15", - ... -} -``` - -To ensure that the values don't change between when you read the configuration and when you update it, you can pass the revision ID from the output of `get-function-configuration` as a parameter to `update-function-configuration`\. - -To configure a function's encryption key, set the `KMSKeyARN` option\. - -``` -$ aws lambda update-function-configuration --function-name my-function \ - --kms-key-arn arn:aws:kms:us-east-2:123456789012:key/055efbb4-xmpl-4336-ba9c-538c7d31f599 -``` - -## Sample code and templates - -Sample applications in this guide's GitHub repository demonstrate the use of environment variables in function code and AWS CloudFormation templates\. - -**Sample applications** -+ [Blank](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/blank) – Create a function and an Amazon SNS topic in the same template\. Pass the name of the topic to the function in an environment variable\. Read environment variables in code \(multiple languages\)\. -+ [RDS MySQL](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/rds-mysql) – Create a VPC and an Amazon RDS DB instance in one template, with a password stored in Secrets Manager\. In the application template, import database details from the VPC stack, read the password from Secrets Manager, and pass all connection configuration to the function in environment variables\. \ No newline at end of file diff --git a/doc_source/configuration-layers.md b/doc_source/configuration-layers.md deleted file mode 100644 index e494bdf2..00000000 --- a/doc_source/configuration-layers.md +++ /dev/null @@ -1,213 +0,0 @@ -# AWS Lambda layers - -You can configure your Lambda function to pull in additional code and content in the form of layers\. A layer is a ZIP archive that contains libraries, a [custom runtime](runtimes-custom.md), or other dependencies\. With layers, you can use libraries in your function without needing to include them in your deployment package\. - -Layers let you keep your deployment package small, which makes development easier\. You can avoid errors that can occur when you install and package dependencies with your function code\. For Node\.js, Python, and Ruby functions, you can [develop your function code in the Lambda console](code-editor.md) as long as you keep your deployment package under 3 MB\. - -**Note** -A function can use up to 5 layers at a time\. The total unzipped size of the function and all layers can't exceed the unzipped deployment package size limit of 250 MB\. For more information, see [AWS Lambda limits](gettingstarted-limits.md)\. - -You can create layers, or use layers published by AWS and other AWS customers\. Layers support [resource\-based policies](#configuration-layers-permissions) for granting layer usage permissions to specific AWS accounts, [AWS Organizations](https://docs.aws.amazon.com/organizations/latest/userguide/), or all accounts\. - -Layers are extracted to the `/opt` directory in the function execution environment\. Each runtime looks for libraries in a different location under `/opt`, depending on the language\. [Structure your layer](#configuration-layers-path) so that function code can access libraries without additional configuration\. - -You can also use AWS Serverless Application Model \(AWS SAM\) to manage layers and your function's layer configuration\. For instructions, see [Declaring serverless resources](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-template.html) in the *AWS Serverless Application Model Developer Guide*\. - -**Topics** -+ [Configuring a function to use layers](#configuration-layers-using) -+ [Managing layers](#configuration-layers-manage) -+ [Including library dependencies in a layer](#configuration-layers-path) -+ [Layer permissions](#configuration-layers-permissions) - -## Configuring a function to use layers - -You can specify up to 5 layers in your function's configuration, during or after function creation\. You choose a specific version of a layer to use\. If you want to use a different version later, update your function's configuration\. - -To add layers to your function, use the `update-function-configuration` command\. The following example adds two layers: one from the same account as the function, and one from a different account\. - -``` -$ aws lambda update-function-configuration --function-name my-function \ ---layers arn:aws:lambda:us-east-2:123456789012:layer:my-layer:3 \ -arn:aws:lambda:us-east-2:210987654321:layer:their-layer:2 -{ - "FunctionName": "test-layers", - "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function", - "Runtime": "nodejs12.x", - "Role": "arn:aws:iam::123456789012:role/service-role/lambda-role", - "Layers": [ - { - "Arn": "arn:aws:lambda:us-east-2:123456789012:layer:my-layer:3", - "CodeSize": 169 - }, - { - "Arn": "arn:aws:lambda:us-east-2:210987654321:layer:their-layer:2", - "CodeSize": 169 - } - ], - "RevisionId": "81cc64f5-5772-449a-b63e-12330476bcc4", - ... -} -``` - -You must specify the version of each layer to use by providing the full ARN of the layer version\. When you add layers to a function that already has layers, the previous list is overwritten by the new one\. Include all layers every time you update the layer configuration\. To remove all layers, specify an empty list\. - -``` -$ aws lambda update-function-configuration --function-name my-function --layers [] -``` - -Your function can access the content of the layer during execution in the `/opt` directory\. Layers are applied in the order that's specified, merging any folders with the same name\. If the same file appears in multiple layers, the version in the last applied layer is used\. - -The creator of a layer can delete the version of the layer that you're using\. When this happens, your function continues to run as though the layer version still existed\. However, when you update the layer configuration, you must remove the reference to the deleted version\. - -## Managing layers - -To create a layer, use the `publish-layer-version` command with a name, description, ZIP archive, and a list of [runtimes](lambda-runtimes.md) that are compatible with the layer\. The list of runtimes is optional, but it makes the layer easier to discover\. - -``` -$ aws lambda publish-layer-version --layer-name my-layer --description "My layer" --license-info "MIT" \ ---content S3Bucket=lambda-layers-us-east-2-123456789012,S3Key=layer.zip --compatible-runtimes python3.6 python3.7 -{ - "Content": { - "Location": "https://awslambda-us-east-2-layers.s3.us-east-2.amazonaws.com/snapshots/123456789012/my-layer-4aaa2fbb-ff77-4b0a-ad92-5b78a716a96a?versionId=27iWyA73cCAYqyH...", - "CodeSha256": "tv9jJO+rPbXUUXuRKi7CwHzKtLDkDRJLB3cC3Z/ouXo=", - "CodeSize": 169 - }, - "LayerArn": "arn:aws:lambda:us-east-2:123456789012:layer:my-layer", - "LayerVersionArn": "arn:aws:lambda:us-east-2:123456789012:layer:my-layer:1", - "Description": "My layer", - "CreatedDate": "2018-11-14T23:03:52.894+0000", - "Version": 1, - "LicenseInfo": "MIT", - "CompatibleRuntimes": [ - "python3.6", - "python3.7", - "python3.8" - ] -} -``` - -Each time you call `publish-layer-version`, you create a new version\. Functions that use the layer refer directly to a layer version\. You can [configure permissions](#configuration-layers-permissions) on an existing layer version, but to make any other changes, you must create a new version\. - - To find layers that are compatible with your function's runtime, use the `list-layers` command\. - -``` -$ aws lambda list-layers --compatible-runtime python3.8 -{ - "Layers": [ - { - "LayerName": "my-layer", - "LayerArn": "arn:aws:lambda:us-east-2:123456789012:layer:my-layer", - "LatestMatchingVersion": { - "LayerVersionArn": "arn:aws:lambda:us-east-2:123456789012:layer:my-layer:2", - "Version": 2, - "Description": "My layer", - "CreatedDate": "2018-11-15T00:37:46.592+0000", - "CompatibleRuntimes": [ - "python3.6", - "python3.7", - "python3.8", - ] - } - } - ] -} -``` - -You can omit the runtime option to list all layers\. The details in the response reflect the latest version of the layer\. See all the versions of a layer with `list-layer-versions`\. To see more information about a version, use `get-layer-version`\. - -``` -$ aws lambda get-layer-version --layer-name my-layer --version-number 2 -{ - "Content": { - "Location": "https://awslambda-us-east-2-layers.s3.us-east-2.amazonaws.com/snapshots/123456789012/my-layer-91e9ea6e-492d-4100-97d5-a4388d442f3f?versionId=GmvPV.309OEpkfN...", - "CodeSha256": "tv9jJO+rPbXUUXuRKi7CwHzKtLDkDRJLB3cC3Z/ouXo=", - "CodeSize": 169 - }, - "LayerArn": "arn:aws:lambda:us-east-2:123456789012:layer:my-layer", - "LayerVersionArn": "arn:aws:lambda:us-east-2:123456789012:layer:my-layer:2", - "Description": "My layer", - "CreatedDate": "2018-11-15T00:37:46.592+0000", - "Version": 2, - "CompatibleRuntimes": [ - "python3.6", - "python3.7", - "python3.8" - ] -} -``` - -The link in the response lets you download the layer archive and is valid for 10 minutes\. To delete a layer version, use the `delete-layer-version` command\. - -``` -$ aws lambda delete-layer-version --layer-name my-layer --version-number 1 -``` - -When you delete a layer version, you can no longer configure functions to use it\. However, any function that already uses the version continues to have access to it\. Version numbers are never re\-used for a layer name\. - -## Including library dependencies in a layer - -You can move runtime dependencies out of your function code by placing them in a layer\. Lambda runtimes include paths in the `/opt` directory to ensure that your function code has access to libraries that are included in layers\. - -To include libraries in a layer, place them in one of the folders supported by your runtime\. -+ **Node\.js** – `nodejs/node_modules`, `nodejs/node8/node_modules` \(`NODE_PATH`\) -**Example AWS X\-Ray SDK for Node\.js** - - ``` - xray-sdk.zip - └ nodejs/node_modules/aws-xray-sdk - ``` -+ **Python** – `python`, `python/lib/python3.8/site-packages` \(site directories\) -**Example Pillow** - - ``` - pillow.zip - │ python/PIL - └ python/Pillow-5.3.0.dist-info - ``` -+ **Java** – `java/lib` \(classpath\) -**Example Jackson** - - ``` - jackson.zip - └ java/lib/jackson-core-2.2.3.jar - ``` -+ **Ruby** – `ruby/gems/2.5.0` \(`GEM_PATH`\), `ruby/lib` \(`RUBYLIB`\) -**Example JSON** - - ``` - json.zip - └ ruby/gems/2.5.0/ - | build_info - | cache - | doc - | extensions - | gems - | └ json-2.1.0 - └ specifications - └ json-2.1.0.gemspec - ``` -+ **All** – `bin` \(`PATH`\), `lib` \(`LD_LIBRARY_PATH`\) -**Example JQ** - - ``` - jq.zip - └ bin/jq - ``` - -For more information about path settings in the Lambda execution environment, see [Runtime environment variables](configuration-envvars.md#configuration-envvars-runtime)\. - -## Layer permissions - -Layer usage permissions are managed on the resource\. To configure a function with a layer, you need permission to call `GetLayerVersion` on the layer version\. For functions in your account, you can get this permission from your [user policy](access-control-identity-based.md) or from the function's [resource\-based policy](access-control-resource-based.md)\. To use a layer in another account, you need permission on your user policy, and the owner of the other account must grant your account permission with a resource\-based policy\. - -To grant layer\-usage permission to another account, add a statement to the layer version's permissions policy with the `add-layer-version-permission` command\. In each statement, you can grant permission to a single account, all accounts, or an organization\. - -``` -$ aws lambda add-layer-version-permission --layer-name xray-sdk-nodejs --statement-id xaccount \ ---action lambda:GetLayerVersion --principal 210987654321 --version-number 1 --output text -e210ffdc-e901-43b0-824b-5fcd0dd26d16 {"Sid":"xaccount","Effect":"Allow","Principal":{"AWS":"arn:aws:iam::210987654321:root"},"Action":"lambda:GetLayerVersion","Resource":"arn:aws:lambda:us-east-2:123456789012:layer:xray-sdk-nodejs:1"} -``` - -Permissions only apply to a single version of a layer\. Repeat the procedure each time you create a new layer version\. - -For more examples, see [Granting layer access to other accounts](access-control-resource-based.md#permissions-resource-xaccountlayer)\. \ No newline at end of file diff --git a/doc_source/configuration-tags.md b/doc_source/configuration-tags.md deleted file mode 100644 index 3e17fd19..00000000 --- a/doc_source/configuration-tags.md +++ /dev/null @@ -1,88 +0,0 @@ -# Tagging Lambda Functions - -You can tag Lambda functions to organize them by owner, project or department\. Tags are freeform key\-value pairs that are supported across AWS services for use in filtering resources and adding detail to billing reports\. - -**To add tags to a function** - -1. Open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions)\. - -1. Choose a function\. - -1. Under **Tags**, choose **Manage tags**\. - -1. Enter a key and value\. To add additional tags, choose **Add new tag**\. -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/configuration-tags-add.png) - -1. Choose **Save**\. - -You can filter functions based on the presence or value of a tag with the Lambda console or with the AWS Resource Groups API\. Tags apply at the function level, not to versions or aliases\. Tags are not part of the version\-specific configuration that is snapshotted when you publish a version\. - -**To filter functions with tags** - -1. Open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions)\. - -1. Click within the search bar to see a list of function attributes and tag keys\. -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/configuration-tags-key.png) - -1. Choose a tag key to see a list of values that are in\-use in the current region\. - -1. Choose a value to see functions with that value, or choose **\(all values\)** to see all functions that have a tag with that key\. -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/configuration-tags-value.png) - -The search bar also supports searching for tag keys\. Type `tag` to see just a list of tag keys, or start typing the name of a key to find it in the list\. - -With AWS Billing and Cost Management, you can use tags to customize billing reports and create cost\-allocation reports\. For more information, see see [Monthly Cost Allocation Report](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/configurecostallocreport.html) and [Using Cost Allocation Tags](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html) in the *AWS Billing and Cost Management User Guide*\. - -**Topics** -+ [Using Tags with the AWS CLI](#configuration-tags-cli) -+ [Tag Key and Value Requirements](#configuration-tags-restrictions) - -## Using Tags with the AWS CLI - -When you create a new Lambda function, you can include tags with the `--tags` option\. - -``` -$ aws lambda create-function --function-name my-function ---handler index.js --runtime nodejs12.x \ ---role arn:aws:iam::123456789012:role/lambda-role \ ---tags Department=Marketing,CostCenter=1234ABCD -``` - -To add tags to an existing function, use the `tag-resource` command\. - -``` -$ aws lambda tag-resource \ ---resource arn:aws:lambda:us-east-2:123456789012:function:my-function \ ---tags Department=Marketing,CostCenter=1234ABCD -``` - -To remove tags, use the `untag-resource` command\. - -``` -$ aws lambda untag-resource --resource function arn \ ---tag-keys Department -``` - -If you want to view the tags that are applied to a specific Lambda function, you can use either of the following Lambda API commands: -+ [ListTags](API_ListTags.md) – You supply your Lambda function ARN \(Amazon Resource Name\) to view a list of the tags associated with this function: - - ``` - $ aws lambda list-tags --resource function arn - ``` -+ [GetFunction](API_GetFunction.md) – You supply your Lambda function name to a view a list of the tags associated with this function: - - ``` - $ aws lambda get-function --function-name my-function - ``` - -You can also use the AWS Tagging Service’s [GetResources](https://docs.aws.amazon.com/resourcegroupstagging/latest/APIReference/API_GetResources.html) API to filter your resources by tags\. The GetResources API receives up to 10 filters, with each filter containing a tag key and up to 10 tag values\. You provide GetResources with a ‘ResourceType’ to filter by specific resource types\. For more information about the AWS Tagging Service, see [Working with Resource Groups](https://docs.aws.amazon.com/awsconsolehelpdocs/latest/gsg/resource-groups.html)\. - -## Tag Key and Value Requirements - -The following requirements apply to tags: -+ Maximum number of tags per resource—50 -+ Maximum key length—128 Unicode characters in UTF\-8 -+ Maximum value length—256 Unicode characters in UTF\-8 -+ Tag keys and values are case sensitive\. -+ Do not use the `aws:` prefix in your tag names or values because it is reserved for AWS use\. You can't edit or delete tag names or values with this prefix\. Tags with this prefix do not count against your tags per resource limit\. -+ If your tagging schema will be used across multiple services and resources, remember that other services may have restrictions on allowed characters\. Generally allowed characters are: letters, spaces, and numbers representable in UTF\-8, plus the following special characters: \+ \- = \. \_ : / @\. \ No newline at end of file diff --git a/doc_source/configuration-versions.md b/doc_source/configuration-versions.md deleted file mode 100644 index c674a767..00000000 --- a/doc_source/configuration-versions.md +++ /dev/null @@ -1,75 +0,0 @@ -# AWS Lambda function versions - -You can use versions to manage the deployment of your AWS Lambda functions\. For example, you can publish a new version of a function for beta testing without affecting users of the stable production version\. - -The system creates a new version of your Lambda function each time that you publish the function\. The new version is a copy of the unpublished version of the function\. The function version includes the following information: -+ The function code and all associated dependencies\. -+ The Lambda runtime that executes the function\. -+ All of the function settings, including the environment variables\. -+ A unique Amazon Resource Name \(ARN\) to identify this version of the function\. - -You can change the function code and settings only on the unpublished version of a function\. When you publish a version, the code and most of the settings are locked to ensure a consistent experience for users of that version\. For more information about configuring function settings, see [Configuring functions in the AWS Lambda console](configuration-console.md)\. - -**To create a new version of a function** - -1. Open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions)\. - -1. Choose the function that you want to publish\. - -1. In **Actions**, choose **Publish new version**\. - -After you publish the first version of a function, the Lambda console displays a drop\-down menu of the available versions\. The **Designer** panel displays a version qualifier at the end of the function name\. - -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/version-1-created.png) - -To view the current versions of the function, choose a function, and then choose **Qualifiers**\. In the expanded **Qualifiers** menu, choose the **Versions** tab\. The **Versions** panel displays the list of versions for the selected function\. If you haven't published a version of the selected function, the **Versions** panel lists only the `$LATEST` version\. - -## Managing versions with the Lambda API - -To publish a version of a function, use the [PublishVersion](API_PublishVersion.md) API action\. - -The following example publishes a new version of a function\. The response returns configuration information about the new version, including the version number and the function ARN with the version suffix\. - -``` -$ aws lambda publish-version --function-name my-function -{ - "FunctionName": "my-function", - "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function:1", - "Version": "1", - "Role": "arn:aws:iam::123456789012:role/lambda-role", - "Handler": "function.handler", - "Runtime": "nodejs12.x", - ... -} -``` - -## Using versions - -You reference your Lambda function using its ARN\. There are two ARNs associated with this initial version: -+ **Qualified ARN** – The function ARN with the version suffix\. - - ``` - arn:aws:lambda:aws-region:acct-id:function:helloworld:$LATEST - ``` -+ **Unqualified ARN** – The function ARN without the version suffix\. - - ``` - arn:aws:lambda:aws-region:acct-id:function:helloworld - ``` - - You can use this unqualified ARN in all relevant operations\. However, you can't use it to create an alias\. - -If you decide not to publish function versions, you can use either the qualified or unqualified ARN in your event source mapping to invoke the function\. - -Lambda only publishes a new function version if the code has never been published or if the code has changed compared to the most recently published version\. If there is no change, the function version remains at the most recently published version\. - -Each Lambda function version has a unique ARN\. After you publish a version, you can't change the ARN or the function code\. - -## Resource policies - -When you use a [resource\-based policy](access-control-resource-based.md) to give a service, resource, or account access to your function, the scope of that permission depends on whether you applied it to a function or to one version of a function: -+ If you use a qualified function name \(such as `helloworld:1`\), the permission is valid for invoking the `helloworld` function version 1 *only* using its qualified ARN\. Using any other ARNs results in a permission error\. -+ If you use an unqualified function name \(such as `helloworld`\), the permission is valid only for invoking the `helloworld` function using the unqualified function ARN\. Using any other ARNs, including `$LATEST`, results in a permission error\. -+ If you use the `$LATEST` qualified function name \(such as `helloworld:$LATEST`\), the permission is valid for invoking the `helloworld` function *only* using its qualified ARN\. Using an unqualified ARN results in a permission error\. - -You can simplify the management of event sources and resource policies by using function aliases\. For more information, see [AWS Lambda function aliases](configuration-aliases.md)\. \ No newline at end of file diff --git a/doc_source/configuration-vpc.md b/doc_source/configuration-vpc.md deleted file mode 100644 index 3b4e6ca0..00000000 --- a/doc_source/configuration-vpc.md +++ /dev/null @@ -1,101 +0,0 @@ -# Configuring a Lambda function to access resources in a VPC - -You can configure a function to connect to private subnets in a virtual private cloud \(VPC\) in your account\. Use Amazon Virtual Private Cloud \(Amazon VPC\) to create a private network for resources such as databases, cache instances, or internal services\. Connect your function to the VPC to access private resources during execution\. - -**To connect a function to a VPC** - -1. Open the [Lambda console](https://console.aws.amazon.com/lambda)\. - -1. Choose a function\. - -1. Under **VPC**, choose **Edit**\. - -1. Choose **Custom VPC**\. - -1. Choose a VPC, subnets, and security groups\. -**Note** -Connect your function to private subnets to access private resources\. If your function needs internet access, use [NAT](#vpc-internet)\. Connecting a function to a public subnet does not give it internet access or a public IP address\. - -1. Choose **Save**\. - -When you connect a function to a VPC, Lambda creates an [elastic network interface](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_ElasticNetworkInterfaces.html) for each combination of security group and subnet in your function's VPC configuration\. This process can take about a minute\. During this time, you cannot perform additional operations that target the function, such as [creating versions](configuration-versions.md) or updating the function's code\. For new functions, you can't invoke the function until its state transitions from `Pending` to `Active`\. For existing functions, you can still invoke the old version while the update is in progress\. For more information about function states, see [Monitoring the state of a function with the Lambda API](functions-states.md)\. - -Multiple functions connected to the same subnets share network interfaces, so connecting additional functions to a subnet that already has a Lambda\-managed network interface is much quicker\. However, Lambda might create additional network interfaces if you have many functions or very busy functions\. - -If your functions are not active for a long period of time, Lambda reclaims its network interfaces, and the function becomes `Idle`\. Invoke an idle function to reactivate it\. The first invocation fails and the function enters a pending state again until the network interface is available\. - -Lambda functions cannot connect directly to a VPC with [dedicated instance tenancy](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/dedicated-instance.html)\. To connect to resources in a dedicated VPC, [peer it to a second VPC with default tenancy](https://aws.amazon.com/premiumsupport/knowledge-center/lambda-dedicated-vpc/)\. - -**VPC tutorials** -+ [Tutorial: Configuring a Lambda function to access Amazon RDS in an Amazon VPC](services-rds-tutorial.md) -+ [Tutorial: Configuring a Lambda function to access Amazon ElastiCache in an Amazon VPC](services-elasticache-tutorial.md) - -**Topics** -+ [Execution role and user permissions](#vpc-permissions) -+ [Configuring Amazon VPC access with the Lambda API](#vpc-configuring) -+ [Internet and service access for VPC\-connected functions](#vpc-internet) -+ [Sample VPC configurations](#vpc-samples) - -## Execution role and user permissions - -Lambda uses your function's permissions to create and manage network interfaces\. To connect to a VPC, your function's execution role must have the following permissions\. - -**Execution role permissions** -+ **ec2:CreateNetworkInterface** -+ **ec2:DescribeNetworkInterfaces** -+ **ec2:DeleteNetworkInterface** - -These permissions are included in the **AWSLambdaVPCAccessExecutionRole** managed policy\. - -When you configure VPC connectivity, Lambda uses your permissions to verify network resources\. To configure a function to connect to a VPC, your IAM user need the following permissions\. - -**User permissions** -+ **ec2:DescribeSecurityGroups** -+ **ec2:DescribeSubnets** -+ **ec2:DescribeVpcs** - -## Configuring Amazon VPC access with the Lambda API - -You can connect a function to a VPC with the following APIs\. -+ [CreateFunction](API_CreateFunction.md) -+ [UpdateFunctionConfiguration](API_UpdateFunctionConfiguration.md) - -To connect your function to a VPC during creation with the AWS CLI, use the `vpc-config` option with a list of private subnet IDs and security groups\. The following example creates a function with a connection to a VPC with two subnets and one security group\. - -``` -$ aws lambda create-function --function-name my-function \ ---runtime nodejs12.x --handler index.js --zip-file fileb://function.zip \ ---role arn:aws:iam::123456789012:role/lambda-role \ ---vpc-config SubnetIds=subnet-071f712345678e7c8,subnet-07fd123456788a036,SecurityGroupIds=sg-085912345678492fb -``` - -To connect an existing function, use the `vpc-config` option with the `update-function-configuration` command\. - -``` -$ aws lambda update-function-configuration --function-name my-function \ ---vpc-config SubnetIds=subnet-071f712345678e7c8,subnet-07fd123456788a036,SecurityGroupIds=sg-085912345678492fb -``` - -To disconnect your function from a VPC, update the function configuration with an empty list of subnets and security groups\. - -``` -$ aws lambda update-function-configuration --function-name my-function \ ---vpc-config SubnetIds=[],SecurityGroupIds=[] -``` - -## Internet and service access for VPC\-connected functions - -By default, Lambda runs your functions in a secure VPC with access to AWS services and the internet\. The VPC is owned by Lambda and does not connect to your account's default VPC\. When you connect a function to a VPC in your account, it does not have access to the internet unless your VPC provides access\. - -**Note** -Several services offer [VPC endpoints](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-endpoints.html)\. You can use VPC endpoints to connect to AWS services from within a VPC without internet access\. - -Internet access from a private subnet requires network address translation \(NAT\)\. To give your function access to the internet, route outbound traffic to a NAT gateway in a public subnet\. The NAT gateway has a public IP address and can connect to the internet through the VPC's internet gateway\. For more information, see [NAT gateways](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html) in the *Amazon VPC User Guide*\. - -## Sample VPC configurations - -Sample AWS CloudFormation templates for VPC configurations that you can use with Lambda functions are available in this guide's GitHub repository\. There are two templates: -+ [vpc\-private\.yaml](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/templates/vpc-private.yaml) – A VPC with two private subnets and VPC endpoints for Amazon Simple Storage Service and Amazon DynamoDB\. You can use this template to create a VPC for functions that do not need internet access\. This configuration supports use of Amazon S3 and DynamoDB with the AWS SDK, and access to database resources in the same VPC over a local network connection\. -+ [vpc\-privatepublic\.yaml](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/templates/vpc-privatepublic.yaml) – A VPC with two private subnets, VPC endpoints, a public subnet with a NAT gateway, and an internet gateway\. Internet\-bound traffic from functions in the private subnets is routed to the NAT gateway by a route table\. - -To use a template to create a VPC, choose **Create stack** in the [AWS CloudFormation console](https://console.aws.amazon.com/cloudformation) and follow the instructions\. \ No newline at end of file diff --git a/doc_source/csharp-context.md b/doc_source/csharp-context.md deleted file mode 100644 index 539c4cec..00000000 --- a/doc_source/csharp-context.md +++ /dev/null @@ -1,28 +0,0 @@ -# AWS Lambda context object in C\# - -When Lambda runs your function, it passes a context object to the [handler](csharp-handler.md)\. This object provides properties with information about the invocation, function, and execution environment\. - -**Context properties** -+ `FunctionName` – The name of the Lambda function\. -+ `FunctionVersion` – The [version](configuration-versions.md) of the function\. -+ `InvokedFunctionArn` – The Amazon Resource Name \(ARN\) that's used to invoke the function\. Indicates if the invoker specified a version number or alias\. -+ `MemoryLimitInMB` – The amount of memory that's allocated for the function\. -+ `AwsRequestId` – The identifier of the invocation request\. -+ `LogGroupName` – The log group for the function\. -+ `LogStreamName` – The log stream for the function instance\. -+ `RemainingTime` \(`TimeSpan`\) – The number of milliseconds left before the execution times out\. -+ `Identity` – \(mobile apps\) Information about the Amazon Cognito identity that authorized the request\. -+ `ClientContext` – \(mobile apps\) Client context that's provided to Lambda by the client application\. -+ `Logger` The [logger object](csharp-logging.md) for the function\. - - The following C\# code snippet shows a simple handler function that prints some of the context information\. - -``` -public async Task Handler(ILambdaContext context) -{ - Console.WriteLine("Function name: " + context.FunctionName); - Console.WriteLine("RemainingTime: " + context.RemainingTime); - await Task.Delay(TimeSpan.FromSeconds(0.42)); - Console.WriteLine("RemainingTime after sleep: " + context.RemainingTime); -} -``` \ No newline at end of file diff --git a/doc_source/csharp-exceptions.md b/doc_source/csharp-exceptions.md deleted file mode 100644 index 3384f72a..00000000 --- a/doc_source/csharp-exceptions.md +++ /dev/null @@ -1,119 +0,0 @@ -# AWS Lambda function errors in C\# - -When an exception occurs in your Lambda function, Lambda will report the exception information back to you\. Exceptions can occur in two different places: -+ Initialization \(Lambda loading your code, validating the handler string, and creating an instance of your class if it is non\-static\)\. -+ The Lambda function invocation\. - -The serialized exception information is returned as the payload as a modeled JSON object and outputted to CloudWatch logs\. - -In the initialization phase, exceptions can be thrown for invalid handler strings, a rule\-breaking type or method \(see [Lambda function handler restrictions ](csharp-handler.md#csharp-handler-restrictions)\), or any other validation method \(such as forgetting the serializer attribute and having a POCO as your input or output type\)\. These exceptions are of type `LambdaException`\. For example: - -``` -{ - "errorType": "LambdaException", - "errorMessage": "Invalid lambda function handler: 'http://this.is.not.a.valid.handler/'. - The valid format is 'ASSEMBLY::TYPE::METHOD'." -} -``` - -If your constructor throws an exception, the error type is also of type `LambdaException`, but the exception thrown during construction is provided in the `cause` property, which is itself a modeled exception object: - -``` -{ - "errorType": "LambdaException", - "errorMessage": "An exception was thrown when the constructor for type 'LambdaExceptionTestFunction.ThrowExceptionInConstructor' - was invoked. Check inner exception for more details.", - "cause": { - "errorType": "TargetInvocationException", - "errorMessage": "Exception has been thrown by the target of an invocation.", - "stackTrace": [ - "at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean&canBeCached, - RuntimeMethodHandleInternal&ctor, Boolean& bNeedSecurityCheck)", - "at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)", - "at System.Activator.CreateInstance(Type type, Boolean nonPublic)", - "at System.Activator.CreateInstance(Type type)" - ], - "cause": { - "errorType": "ArithmeticException", - "errorMessage": "Sorry, 2 + 2 = 5", - "stackTrace": [ - "at LambdaExceptionTestFunction.ThrowExceptionInConstructor..ctor()" - ] - } - } -} -``` - -As the example shows, the inner exceptions are always preserved \(as the `cause` property\), and can be deeply nested\. - -Exceptions can also occur during invocation\. In this case, the exception type is preserved and the exception is returned directly as the payload and in the CloudWatch logs\. For example: - -``` -{ - "errorType": "AggregateException", - "errorMessage": "One or more errors occurred. (An unknown web exception occurred!)", - "stackTrace": [ - "at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)", - "at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)", - "at lambda_method(Closure , Stream , Stream , ContextInfo )" - ], - "cause": { - "errorType": "UnknownWebException", - "errorMessage": "An unknown web exception occurred!", - "stackTrace": [ - "at LambdaDemo107.LambdaEntryPoint.d__1.MoveNext()", - "--- End of stack trace from previous location where exception was thrown ---", - "at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)", - "at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)", - "at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()", - "at LambdaDemo107.LambdaEntryPoint.d__0.MoveNext()" - ], - "cause": { - "errorType": "WebException", - "errorMessage": "An error occurred while sending the request. SSL peer certificate or SSH remote key was not OK", - "stackTrace": [ - "at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)", - "at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)", - "--- End of stack trace from previous location where exception was thrown ---", - "at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)", - "at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)", - "at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()", - "at LambdaDemo107.LambdaEntryPoint.d__1.MoveNext()" - ], - "cause": { - "errorType": "HttpRequestException", - "errorMessage": "An error occurred while sending the request.", - "stackTrace": [ - "at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)", - "at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)", - "at System.Net.Http.HttpClient.d__58.MoveNext()", - "--- End of stack trace from previous location where exception was thrown ---", - "at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)", - "at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)", - "at System.Net.HttpWebRequest.d__63.MoveNext()", - "--- End of stack trace from previous location where exception was thrown ---", - "at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)", - "at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)", - "at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)" - ], - "cause": { - "errorType": "CurlException", - "errorMessage": "SSL peer certificate or SSH remote key was not OK", - "stackTrace": [ - "at System.Net.Http.CurlHandler.ThrowIfCURLEError(CURLcode error)", - "at System.Net.Http.CurlHandler.MultiAgent.FinishRequest(StrongToWeakReference`1 easyWrapper, CURLcode messageResult)" - ] - } - } - } - } -} -``` - -The method in which error information is conveyed depends on the invocation type: -+ `RequestResponse` invocation type \(that is, synchronous execution\): In this case, you get the error message back\. - - For example, if you invoke a Lambda function using the Lambda console, the `RequestResponse` is always the invocation type and the console displays the error information returned by AWS Lambda in the **Execution result** section of the console\. -+ `Event` invocation type \(that is, asynchronous execution\): In this case AWS Lambda does not return anything\. Instead, it logs the error information in CloudWatch Logs and CloudWatch metrics\. - -Depending on the event source, AWS Lambda may retry the failed Lambda function\. For more information, see [Error handling and automatic retries in AWS Lambda](invocation-retries.md)\. \ No newline at end of file diff --git a/doc_source/csharp-handler.md b/doc_source/csharp-handler.md deleted file mode 100644 index 36a2cdfe..00000000 --- a/doc_source/csharp-handler.md +++ /dev/null @@ -1,215 +0,0 @@ -# AWS Lambda function handler in C\# - -When you create a Lambda function, you specify a handler that AWS Lambda can invoke when the service executes the function on your behalf\. - -You define a Lambda function handler as an instance or static method in a class\. If you want access to the Lambda context object, it is available by defining a method parameter of type *ILambdaContext*, an interface you can use to access information about the current execution, such as the name of the current function, the memory limit, execution time remaining, and logging\. - -``` -returnType handler-name(inputType input, ILambdaContext context) { - ... -} -``` - -In the syntax, note the following: -+ *inputType* – The first handler parameter is the input to the handler, which can be event data \(published by an event source\) or custom input that you provide such as a string or any custom data object\. -+ *returnType* – If you plan to invoke the Lambda function synchronously \(using the `RequestResponse` invocation type\), you can return the output of your function using any of the supported data types\. For example, if you use a Lambda function as a mobile application backend, you are invoking it synchronously\. Your output data type will be serialized into JSON\. - - If you plan to invoke the Lambda function asynchronously \(using the `Event` invocation type\), the `returnType` should be `void`\. For example, if you use AWS Lambda with event sources such as Amazon S3 or Amazon SNS, these event sources invoke the Lambda function using the `Event` invocation type\. -+ `ILambdaContext context` – The second argument in the handler signature is optional\. It provides access to the [context object](csharp-context.md) which has information about the function and request\. - -## Handling streams - -Only the `System.IO.Stream` type is supported as an input parameter by default\. - -For example, consider the following C\# example code\. - -``` -using System.IO; - -namespace Example -{ - public class Hello - { - public Stream MyHandler(Stream stream) - { - //function logic - } - } -} -``` - -In the example C\# code, the first handler parameter is the input to the handler \(MyHandler\), which can be event data \(published by an event source such as Amazon S3\) or custom input you provide such as a `Stream` \(as in this example\) or any custom data object\. The output is of type `Stream`\. - -## Handling standard data types - -All other types, as listed below, require you to specify a serializer\. -+ Primitive \.NET types \(such as string or int\)\. -+ Collections and maps \- IList, IEnumerable, IList, Array, IDictionary, IDictionary -+ POCO types \(Plain old CLR objects\) -+ Predefined AWS event types -+ For asynchronous invocations the return\-type will be ignored by Lambda\. The return type may be set to void in such cases\. -+ If you are using \.NET asynchronous programming, the return type can be Task and Task types and use `async` and `await` keywords\. For more information, see [Using async in C\# functions with AWS Lambda](#csharp-handler-async)\. - -Unless your function input and output parameters are of type `System.IO.Stream`, you will need to serialize them\. AWS Lambda provides a default serializer that can be applied at the assembly or method level of your application, or you can define your own by implementing the `ILambdaSerializer` interface provided by the `Amazon.Lambda.Core` library\. For more information, see [AWS Lambda Deployment Package in C\#](csharp-package.md)\. - - To add the default serializer attribute to a method, first add a dependency on `Amazon.Lambda.Serialization.Json` in your `project.json` file\. - -``` -{ - "version": "1.0.0-*", - "dependencies":{ - "Microsoft.NETCore.App": { - "type": "platform", - "version": "1.0.1" - }, - "Amazon.Lambda.Serialization.Json": "1.3.0" - }, - "frameworks": { - "netcoreapp1.0": { - "imports": "dnxcore50" - } - } -} -``` - - The example below illustrates the flexibility you can leverage by specifying the default Json\.NET serializer on one method and another of your choosing on a different method: - -``` -public class ProductService{ - [LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] - public Product DescribeProduct(DescribeProductRequest request) - { - return catalogService.DescribeProduct(request.Id); - } - - [LambdaSerializer(typeof(MyJsonSerializer))] - public Customer DescribeCustomer(DescribeCustomerRequest request) - { - return customerService.DescribeCustomer(request.Id); - } -} -``` - -## Handler signatures - -When creating Lambda functions, you have to provide a handler string that tells AWS Lambda where to look for the code to invoke\. In C\#, the format is: - - *ASSEMBLY::TYPE::METHOD* where: -+ *ASSEMBLY* is the name of the \.NET assembly file for your application\. When using the \.NET Core CLI to build your application, if you haven't set the assembly name using the `buildOptions.outputName` setting in project\.json, the *ASSEMBLY* name will be the name of the folder that contains your project\.json file\. For more information, see [\.NET Core CLI](csharp-package-cli.md)\. In this case, let's assume the folder name is `HelloWorldApp`\. -+ *TYPE* is the full name of the handler type, which consists of the *Namespace* and the *ClassName*\. In this case `Example.Hello`\. -+ *METHOD* is name of the function handler, in this case `MyHandler`\. - -Ultimately, the signature will be of this format: *Assembly::Namespace\.ClassName::MethodName* - -Again, consider the following example: - -``` -using System.IO; - -namespace Example -{ - public class Hello - { - public Stream MyHandler(Stream stream) - { - //function logic - } - } -} -``` - -The handler string would be: `HelloWorldApp::Example.Hello::MyHandler` - -**Important** -If the method specified in your handler string is overloaded, you must provide the exact signature of the method Lambda should invoke\. AWS Lambda will reject an otherwise valid signature if the resolution would require selecting among multiple \(overloaded\) signatures\. - -## Serializing Lambda functions - -For any Lambda functions that use input or output types other than a `Stream` object, you will need to add a serialization library to your application\. You can do this in the following ways: -+ Use the `Amazon.Lambda.Serialization.Json` NuGet package\. This library uses JSON\.NET to handle serialization\. -+ Create your own serialization library by implementing the `ILambdaSerializer` interface, which is available as part of the `Amazon.Lambda.Core` library\. The interface defines two methods: - + `T Deserialize(Stream requestStream);` - - You implement this method to deserialize the request payload from the `Invoke` API into the object that is passed to the Lambda function handler\. - + `T Serialize(T response, Stream responseStream);`\. - - You implement this method to serialize the result returned from the Lambda function handler into the response payload that is returned by the `Invoke` API\. - -You use whichever serializer you wish by adding it as a dependency to your `MyProject.csproj` file\. - -``` -... - - - - -``` - -You then add it to your AssemblyInfo\.cs file\. For example, if you are using the default Json\.NET serializer, this is what you would add: - -``` -[assembly:LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] -``` - -**Note** -You can define a custom serialization attribute at the method level, which will override the default serializer specified at the assembly level\. For more information, see [Handling standard data types](#csharp-handler-types)\. - -## Lambda function handler restrictions - -Note that there are some restrictions on the handler signature\. -+ It may not be `unsafe` and use pointer types in the handler signature, though `unsafe` context can be used inside the handler method and its dependencies\. For more information, see [unsafe \(C\# reference\)](https://msdn.microsoft.com/en-us/library/chfa2zb8.aspx)\. -+ It may not pass a variable number of parameters using the `params` keyword, or use `ArgIterator` as an input or return parameter which is used to support variable number of parameters\. -+ The handler may not be a generic method \(e\.g\. IList Sort\(IList input\)\)\. -+ Async handlers with signature `async void` are not supported\. - -## Using async in C\# functions with AWS Lambda - -If you know your Lambda function will require a long\-running process, such as uploading large files to Amazon S3 or reading a large stream of records from DynamoDB, you can take advantage of the async/await pattern\. When you use this signature, Lambda executes the function synchronously and waits for the function to return a response or for execution to [time out](configuration-console.md)\. - -``` -public async Task ProcessS3ImageResizeAsync(SimpleS3Event input) -{ - var response = await client.DoAsyncWork(input); - return response; -} -``` - -If you use this pattern, there are some considerations you must take into account: -+ AWS Lambda does not support `async void` methods\. -+ If you create an async Lambda function without implementing the `await` operator, \.NET will issue a compiler warning and you will observe unexpected behavior\. For example, some async actions will execute while others won't\. Or some async actions won't complete before the function execution is complete\. - - ``` - public async Task ProcessS3ImageResizeAsync(SimpleS3Event event) // Compiler warning - { - client.DoAsyncWork(input); - } - ``` -+ Your Lambda function can include multiple async calls, which can be invoked in parallel\. You can use the `Task.WhenAll` and `Task.WhenAny` methods to work with multiple tasks\. To use the `Task.WhenAll` method, you pass a list of the operations as an array to the method\. Note that in the example below, if you neglect to include any operation to the array, that call may return before its operation completes\. - - ``` - public async Task DoesNotWaitForAllTasks1() - { - // In Lambda, Console.WriteLine goes to CloudWatch Logs. - var task1 = Task.Run(() => Console.WriteLine("Test1")); - var task2 = Task.Run(() => Console.WriteLine("Test2")); - var task3 = Task.Run(() => Console.WriteLine("Test3")); - - // Lambda may return before printing "Test2" since we never wait on task2. - await Task.WhenAll(task1, task3); - } - ``` - - To use the `Task.WhenAny` method, you again pass a list of operations as an array to the method\. The call returns as soon as the first operation completes, even if the others are still running\. - - ``` - public async Task DoesNotWaitForAllTasks2() - { - // In Lambda, Console.WriteLine goes to CloudWatch Logs. - var task1 = Task.Run(() => Console.WriteLine("Test1")); - var task2 = Task.Run(() => Console.WriteLine("Test2")); - var task3 = Task.Run(() => Console.WriteLine("Test3")); - - // Lambda may return before printing all tests since we're only waiting for one to finish. - await Task.WhenAny(task1, task2, task3); - } - ``` \ No newline at end of file diff --git a/doc_source/csharp-logging.md b/doc_source/csharp-logging.md deleted file mode 100644 index 31650878..00000000 --- a/doc_source/csharp-logging.md +++ /dev/null @@ -1,182 +0,0 @@ -# AWS Lambda function logging in C\# - -Your Lambda function comes with a CloudWatch Logs log group, with a log stream for each instance of your function\. The runtime sends details about each invocation to the log stream, and relays logs and other output from your function's code\. - -To output logs from your function code, you can use methods on [the Console class](https://docs.microsoft.com/en-us/dotnet/api/system.console), or any logging library that writes to `stdout` or `stderr`\. The following example uses the `LambdaLogger` class from the [Amazon\.Lambda\.Core](lambda-csharp.md) library\. - -**Example [src/blank\-csharp/Function\.cs](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/blank-csharp/src/blank-csharp/Function.cs) – Logging** - -``` -public async Task FunctionHandler(SQSEvent invocationEvent, ILambdaContext context) - { - GetAccountSettingsResponse accountSettings; - try - { - accountSettings = await callLambda(); - } - catch (AmazonLambdaException ex) - { - throw ex; - } - AccountUsage accountUsage = accountSettings.AccountUsage; - LambdaLogger.Log("ENVIRONMENT VARIABLES: " + JsonConvert.SerializeObject(System.Environment.GetEnvironmentVariables())); - LambdaLogger.Log("CONTEXT: " + JsonConvert.SerializeObject(context)); - LambdaLogger.Log("EVENT: " + JsonConvert.SerializeObject(invocationEvent)); - return accountUsage; - } -``` - -**Example Log format** - -``` -START RequestId: d1cf0ccb-xmpl-46e6-950d-04c96c9b1c5d Version: $LATEST -ENVIRONMENT VARIABLES: -{ - "AWS_EXECUTION_ENV": "AWS_Lambda_dotnetcore2.1", - "AWS_LAMBDA_FUNCTION_MEMORY_SIZE": "256", - "AWS_LAMBDA_LOG_GROUP_NAME": "/aws/lambda/blank-csharp-function-WU56XMPLV2XA", - "AWS_LAMBDA_FUNCTION_VERSION": "$LATEST", - "AWS_LAMBDA_LOG_STREAM_NAME": "2020/03/27/[$LATEST]5296xmpl084f411d9fb73b258393f30c", - "AWS_LAMBDA_FUNCTION_NAME": "blank-csharp-function-WU56XMPLV2XA", - ... -EVENT: -{ - "Records": [ - { - "MessageId": "19dd0b57-b21e-4ac1-bd88-01bbb068cb78", - "ReceiptHandle": "MessageReceiptHandle", - "Body": "Hello from SQS!", - "Md5OfBody": "7b270e59b47ff90a553787216d55d91d", - "Md5OfMessageAttributes": null, - "EventSourceArn": "arn:aws:sqs:us-west-2:123456789012:MyQueue", - "EventSource": "aws:sqs", - "AwsRegion": "us-west-2", - "Attributes": { - "ApproximateReceiveCount": "1", - "SentTimestamp": "1523232000000", - "SenderId": "123456789012", - "ApproximateFirstReceiveTimestamp": "1523232000001" - }, - ... -END RequestId: d1cf0ccb-xmpl-46e6-950d-04c96c9b1c5d -REPORT RequestId: d1cf0ccb-xmpl-46e6-950d-04c96c9b1c5d Duration: 4157.16 ms Billed Duration: 4200 ms Memory Size: 256 MB Max Memory Used: 99 MB Init Duration: 841.60 ms -XRAY TraceId: 1-5e7e8131-7ff0xmpl32bfb31045d0a3bb SegmentId: 0152xmpl6016310f Sampled: true -``` - -The \.NET runtime logs the `START`, `END`, and `REPORT` lines for each invocation\. The report line provides the following details\. - -**Report Log** -+ **RequestId** – The unique request ID for the invocation\. -+ **Duration** – The amount of time that your function's handler method spent processing the event\. -+ **Billed Duration** – The amount of time billed for the invocation\. -+ **Memory Size** – The amount of memory allocated to the function\. -+ **Max Memory Used** – The amount of memory used by the function\. -+ **Init Duration** – For the first request served, the amount of time it took the runtime to load the function and run code outside of the handler method\. -+ **XRAY TraceId** – For traced requests, the [AWS X\-Ray trace ID](lambda-x-ray.md)\. -+ **SegmentId** – For traced requests, the X\-Ray segment ID\. -+ **Sampled** – For traced requests, the sampling result\. - -You can view logs in the Lambda console, in the CloudWatch Logs console, or from the command line\. - -**Topics** -+ [Viewing logs in the AWS Management Console](#csharp-logging-console) -+ [Using the AWS CLI](#csharp-logging-cli) -+ [Deleting logs](#csharp-logging-delete) - -## Viewing logs in the AWS Management Console - -The Lambda console shows log output when you test a function on the function configuration page\. To view logs for all invocations, use the CloudWatch Logs console\. - -**To view your Lambda function's logs** - -1. Open the [Logs page of the CloudWatch console](https://console.aws.amazon.com/cloudwatch/home?#logs:)\. - -1. Choose the log group for your function \(**/aws/lambda/*function\-name***\)\. - -1. Choose the first stream in the list\. - -Each log stream corresponds to an [instance of your function](runtimes-context.md)\. New streams appear when you update your function and when additional instances are created to handle multiple concurrent invocations\. To find logs for specific invocations, you can instrument your function with X\-Ray, and record details about the request and log stream in the trace\. For a sample application that correlates logs and traces with X\-Ray, see [Error processor sample application for AWS Lambda](samples-errorprocessor.md)\. - -## Using the AWS CLI - -To get logs for an invocation from the command line, use the `--log-type` option\. The response includes a `LogResult` field that contains up to 4 KB of base64\-encoded logs from the invocation\. - -``` -$ aws lambda invoke --function-name my-function out --log-type Tail -{ - "StatusCode": 200, - "LogResult": "U1RBUlQgUmVxdWVzdElkOiA4N2QwNDRiOC1mMTU0LTExZTgtOGNkYS0yOTc0YzVlNGZiMjEgVmVyc2lvb...", - "ExecutedVersion": "$LATEST" -} -``` - -You can use the `base64` utility to decode the logs\. - -``` -$ aws lambda invoke --function-name my-function out --log-type Tail \ ---query 'LogResult' --output text | base64 -d -START RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 Version: $LATEST - "AWS_SESSION_TOKEN": "AgoJb3JpZ2luX2VjELj...", "_X_AMZN_TRACE_ID": "Root=1-5d02e5ca-f5792818b6fe8368e5b51d50;Parent=191db58857df8395;Sampled=0"",ask/lib:/opt/lib", -END RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 -REPORT RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 Duration: 79.67 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 73 MB -``` - -The `base64` utility is available on Linux, macOS, and [Ubuntu on Windows](https://docs.microsoft.com/en-us/windows/wsl/install-win10)\. For macOS, the command is `base64 -D`\. - -To get full log events from the command line, you can include the log stream name in the output of your function, as shown in the preceding example\. The following example script invokes a function named `my-function` and downloads the last five log events\. - -**Example get\-logs\.sh Script** -This example requires that `my-function` returns a log stream ID\. - -``` -#!/bin/bash -aws lambda invoke --function-name my-function --payload '{"key": "value"}' out -sed -i'' -e 's/"//g' out -sleep 15 -aws logs get-log-events --log-group-name /aws/lambda/my-function --log-stream-name $(cat out) --limit 5 -``` - -The script uses `sed` to remove quotes from the output file, and sleeps for 15 seconds to allow time for the logs to be available\. The output includes the response from Lambda and the output from the `get-log-events` command\. - -``` -$ ./get-logs.sh -{ - "StatusCode": 200, - "ExecutedVersion": "$LATEST" -} -{ - "events": [ - { - "timestamp": 1559763003171, - "message": "START RequestId: 4ce9340a-b765-490f-ad8a-02ab3415e2bf Version: $LATEST\n", - "ingestionTime": 1559763003309 - }, - { - "timestamp": 1559763003173, - "message": "2019-06-05T19:30:03.173Z\t4ce9340a-b765-490f-ad8a-02ab3415e2bf\tINFO\tENVIRONMENT VARIABLES\r{\r \"AWS_LAMBDA_FUNCTION_VERSION\": \"$LATEST\",\r ...", - "ingestionTime": 1559763018353 - }, - { - "timestamp": 1559763003173, - "message": "2019-06-05T19:30:03.173Z\t4ce9340a-b765-490f-ad8a-02ab3415e2bf\tINFO\tEVENT\r{\r \"key\": \"value\"\r}\n", - "ingestionTime": 1559763018353 - }, - { - "timestamp": 1559763003218, - "message": "END RequestId: 4ce9340a-b765-490f-ad8a-02ab3415e2bf\n", - "ingestionTime": 1559763018353 - }, - { - "timestamp": 1559763003218, - "message": "REPORT RequestId: 4ce9340a-b765-490f-ad8a-02ab3415e2bf\tDuration: 26.73 ms\tBilled Duration: 100 ms \tMemory Size: 128 MB\tMax Memory Used: 75 MB\t\n", - "ingestionTime": 1559763018353 - } - ], - "nextForwardToken": "f/34783877304859518393868359594929986069206639495374241795", - "nextBackwardToken": "b/34783877303811383369537420289090800615709599058929582080" -} -``` - -## Deleting logs - -Log groups aren't deleted automatically when you delete a function\. To avoid storing logs indefinitely, delete the log group, or [configure a retention period](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Working-with-log-groups-and-streams.html#SettingLogRetention) after which logs are deleted automatically\. \ No newline at end of file diff --git a/doc_source/csharp-package-cli.md b/doc_source/csharp-package-cli.md deleted file mode 100644 index fdd45131..00000000 --- a/doc_source/csharp-package-cli.md +++ /dev/null @@ -1,185 +0,0 @@ -# \.NET Core CLI - -The \.NET Core CLI offers a cross\-platform way for you to create \.NET\-based Lambda applications\. This section assumes you have installed the \.NET Core CLI\. If you haven't, do so [here](https://www.microsoft.com/net/download/windows)\. - -In the \.NET CLI, you use the `new` command to create \.NET projects from a command line\. This is useful if you want to create a project outside of Visual Studio\. To view a list of the available project types, open a command line and navigate to where you installed the \.NET Core runtime and run the following command: - -``` -dotnet new -all -Usage: new [options] -... -Templates Short Name Language Tags ----------------------------------------------------------------------------------------------------------------------------- -Console Application console [C#], F#, VB Common/Console -Class library classlib [C#], F#, VB Common/Library -Unit Test Project mstest [C#], F#, VB Test/MSTest -xUnit Test Project xunit [C#], F#, VB Test/xUnit -... -Examples: - dotnet new mvc --auth Individual - dotnet new viewstart - dotnet new --help -``` - -AWS Lambda offers additional templates via the [Amazon\.Lambda\.Templates](https://www.nuget.org/packages/Amazon.Lambda.Templates) nuget package\. To install this package, run the following command: - -``` -dotnet new -i Amazon.Lambda.Templates -``` - -Once the install is complete, the Lambda templates show up as part of `dotnet new`\. To examine details about a template, use the help option\. - -``` -dotnet new lambda.EmptyFunction --help -``` - -The `lambda.EmptyFunction` template supports the following options\. -+ `--name` – The name of the function\. -+ `--profile` – The name of a profile in your [AWS SDK for \.NET credentials file](https://docs.aws.amazon.com/sdk-for-net/latest/developer-guide/net-dg-config-creds.html)\. -+ `--region` – The AWS Region to create the function in\. - -These options are saved to a file named `aws-lambda-tools-defaults.json`\. - -Create a function project with the `lambda.EmptyFunction` template\. - -``` -dotnet new lambda.EmptyFunction --name MyFunction -``` - -Under the `src/myfunction` directory, examine the following files: -+ **aws\-lambda\-tools\-defaults\.json**: This is where you specify the command line options when deploying your Lambda function\. For example: - - ``` - "profile" : "default", - "region" : "us-east-2", - "configuration" : "Release", - "framework" : "netcoreapp2.1", - "function-runtime":"dotnetcore3.1", - "function-memory-size" : 256, - "function-timeout" : 30, - "function-handler" : "MyFunction::MyFunction.Function::FunctionHandler" - ``` -+ **Function\.cs**: Your Lambda handler function code\. It's a C\# template that includes the default `Amazon.Lambda.Core` library and a default `LambdaSerializer` attribute\. For more information on serialization requirements and options, see [Serializing Lambda functions](csharp-handler.md#csharp-handler-serializer)\. It also includes a sample function that you can edit to apply your Lambda function code\. - - ``` - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - - using Amazon.Lambda.Core; - - // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. - [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] - - namespace MyFunction - { - public class Function - { - - public string FunctionHandler1(string input, ILambdaContext context) - { - return input?.ToUpper(); - } - } - } - ``` -+ **MyFunction\.csproj**: An [MSBuild](https://msdn.microsoft.com/en-us/library/dd393574.aspx) file that lists the files and assemblies that comprise your application\. - - ``` - - - - netcoreapp2.1 - - - - - - - - - ``` -+ **Readme**: Use this file to document your Lambda function\. - -Under the `myfunction/test directory, examine the following files:` -+ **myFunction\.Tests\.csproj**: As noted above, this is an [MSBuild](https://msdn.microsoft.com/en-us/library/dd393574.aspx) file that lists the files and assemblies that comprise your test project\. Note also that it includes the `Amazon.Lambda.Core` library, allowing you to seamlesssly integrate any Lambda templates required to test your function\. - - ``` - - ... - - - ... - ``` -+ **FunctionTest\.cs**: The same C\# code template file that it is included in the `src` directory\. Edit this file to mirror your function's production code and test it before uploading your Lambda function to a production environment\. - - ``` - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - - using Xunit; - using Amazon.Lambda.Core; - using Amazon.Lambda.TestUtilities; - - using MyFunction; - - namespace MyFunction.Tests - { - public class FunctionTest - { - [Fact] - public void TestToUpperFunction() - { - - // Invoke the lambda function and confirm the string was upper cased. - var function = new Function(); - var context = new TestLambdaContext(); - var upperCase = function.FunctionHandler("hello world", context); - - Assert.Equal("HELLO WORLD", upperCase); - } - } - } - ``` - -Once your function has passed its tests, you can build and deploy using the Amazon\.Lambda\.Tools \.NET Core Global Tool\. To install the \.NET Core Global Tool run the following command\. - -``` -dotnet tool install -g Amazon.Lambda.Tools -``` - -If you already have the tool installed you can make sure you are using the latest version with the following command\. - -``` -dotnet tool update -g Amazon.Lambda.Tools -``` - -For more information about the Amazon\.Lambda\.Tools \.NET Core Global see its [GitHub repository](https://github.com/aws/aws-extensions-for-dotnet-cli)\. - -With the Amazon\.Lambda\.Tools installed you can deploy your function with the following command: - -``` -dotnet lambda deploy-function MyFunction --function-role role -``` - -After deployment, you can re\-test it in a production environment with the following command and pass in a different value to your Lambda function handler: - -``` -dotnet lambda invoke-function MyFunction --payload "Just Checking If Everything is OK" -``` - -Presuming everything was successful, you should see the following: - -``` -dotnet lambda invoke-function MyFunction --payload "Just Checking If Everything is OK" -Payload: -"JUST CHECKING IF EVERYTHING IS OK" - -Log Tail: -START RequestId: id Version: $LATEST -END RequestId: id -REPORT RequestId: id Duration: 0.99 ms Billed Duration: 100 ms Memory Size: 256 MB Max Memory Used: 12 MB -``` \ No newline at end of file diff --git a/doc_source/csharp-package-toolkit.md b/doc_source/csharp-package-toolkit.md deleted file mode 100644 index c060dc79..00000000 --- a/doc_source/csharp-package-toolkit.md +++ /dev/null @@ -1,50 +0,0 @@ -# AWS Toolkit for Visual Studio - -You can build \.NET\-based Lambda applications using the Lambda plugin to the [AWS Toolkit for Visual Studio](https://aws.amazon.com/visualstudio/)\. The toolkit is available as a [Visual Studio extension](https://marketplace.visualstudio.com/items?itemName=AmazonWebServices.AWSToolkitforVisualStudio2017)\. - -1. Launch Microsoft Visual Studio and choose **New project**\. - - 1. From the **File** menu, choose **New**, and then choose **Project**\. - - 1. In the **New Project** window, choose **AWS Lambda Project \(\.NET Core\)** and then choose **OK**\. - - 1. In the **Select Blueprint** window, you will be presented with the option of selecting from a list of sample applications that will provide you with sample code to get started with creating a \.NET\-based Lambda application\. - - 1. To create a Lambda application from scratch, choose **Empty Function** and then choose **Finish**\. - -1. Examine the `aws-lambda-tools-defaults.json` file, which is created as part of your project\. You can set the options in this file, which is read by the Lambda tooling by default\. The project templates created in Visual Studio set many of these fields with default values\. Note the following fields: - + **profile** – The name of a profile in your [AWS SDK for \.NET credentials file](https://docs.aws.amazon.com/sdk-for-net/latest/developer-guide/net-dg-config-creds.html)\. - + **function\-handler** – This is where the `function handler` is specified, which is why you don't have to set it in the wizard\. However, whenever you rename the *Assembly*, *Namespace*, *Class* or *Function* in your function code, you will need to update the corresponding fields in the `aws-lambda-tools-defaults.json file`\. - - ``` - { - "profile":"default", - "region" : "us-east-2", - "configuration" : "Release", - "framework" : "netcoreapp2.1", - "function-runtime":"dotnetcore3.1", - "function-memory-size" : 256, - "function-timeout" : 30, - "function-handler" : "Assembly::Namespace.Class::Function" - } - ``` - -1. Open the **Function\.cs** file\. You will be provided with a template to implement your Lambda function handler code\. -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/lambda-function.png) - -1. Once you have written the code that represents your Lambda function, you can upload it by right\-clicking the **Project** node in your application and then choosing **Publish to AWS Lambda**\. - -1. In the **Upload Lambda Function** window, type a name for the function or select a previously published function to republish\. Then choose **Next** - -1. In the **Advanced Function Details** window, configure the following options: - + **Role Name** \(required\) – The [IAM role](lambda-intro-execution-role.md) that AWS Lambda assumes when it executes your function\. - + **Environment** – Key\-value pairs that Lambda sets in the execution environment\. [ Use environment variables](configuration-envvars.md) to extend your function's configuration outside of code\. - + **Memory** – The amount of memory available to the function during execution\. Choose an amount [between 128 MB and 3,008 MB](gettingstarted-limits.md) in 64\-MB increments\. - + **Timeout** – The amount of time that Lambda allows a function to run before stopping it\. The default is 3 seconds\. The maximum allowed value is 900 seconds\. - + **VPC** – If your function needs network access to resources that are not available over the internet, [configure it to connect to a VPC](configuration-vpc.md)\. - + **DLQ** – If your function is invoked asynchronously, [choose a queue or topic](invocation-async.md#dlq) to receive failed invocations\. - + **Enable active tracing** – Sample incoming requests and [trace sampled requests with AWS X\-Ray](lambda-x-ray.md)\. - -1. Choose **Next** and then choose **Upload** to deploy your application\. - -For more information, see [Deploying an AWS Lambda Project with the \.NET Core CLI](https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/lambda-cli-publish.html)\. \ No newline at end of file diff --git a/doc_source/csharp-package.md b/doc_source/csharp-package.md deleted file mode 100644 index cf75e455..00000000 --- a/doc_source/csharp-package.md +++ /dev/null @@ -1,9 +0,0 @@ -# AWS Lambda Deployment Package in C\# - -A \.NET Core Lambda deployment package is a zip file of your function's compiled assembly along with all of its assembly dependencies\. The package also contains a `proj.deps.json` file\. This signals to the \.NET Core runtime all of your function's dependencies and a `proj.runtimeconfig.json` file, which is used to configure the \.NET Core runtime\. The \.NET CLI’s `publish` command can create a folder with all of these files, but by default the `proj.runtimeconfig.json` will not be included because a Lambda project is typically configured to be a class library\. To force the `proj.runtimeconfig.json` to be written as part of the `publish` process, pass in the command line argument: `/p:GenerateRuntimeConfigurationFiles=true to the publish command`\. - -Although it is possible to create the deployment package with the `dotnet publish` command, we suggest you create the deployment package with either the [AWS Toolkit for Visual Studio](csharp-package-toolkit.md) or the [\.NET Core CLI](csharp-package-cli.md)\. These are tools optimized specifically for Lambda to ensure the `lambda-project.runtimeconfig.json` file exists and optimizes the package bundle, including the removal of any non\-Linux\-based dependencies\. - -**Topics** -+ [\.NET Core CLI](csharp-package-cli.md) -+ [AWS Toolkit for Visual Studio](csharp-package-toolkit.md) \ No newline at end of file diff --git a/doc_source/deploying-lambda-apps.md b/doc_source/deploying-lambda-apps.md deleted file mode 100644 index b4cf0b26..00000000 --- a/doc_source/deploying-lambda-apps.md +++ /dev/null @@ -1,16 +0,0 @@ -# AWS Lambda applications - -An AWS Lambda application is a combination of Lambda functions, event sources, and other resources that work together to perform tasks\. You can use AWS CloudFormation and other tools to collect your application's components into a single package that can be deployed and managed as one resource\. Applications make your Lambda projects portable and enable you to integrate with additional developer tools, such as AWS CodePipeline, AWS CodeBuild, and the AWS Serverless Application Model command line interface \(SAM CLI\)\. - -The [AWS Serverless Application Repository](https://docs.aws.amazon.com/serverlessrepo/latest/devguide/) provides a collection of Lambda applications that you can deploy in your account with a few clicks\. The repository includes both ready\-to\-use applications and samples that you can use as a starting point for your own projects\. You can also submit your own projects for inclusion\. - -[AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-whatis-concepts.html) enables you to create a template that defines your application's resources and lets you manage the application as a *stack*\. You can more safely add or modify resources in your application stack\. If any part of an update fails, AWS CloudFormation automatically rolls back to the previous configuration\. With AWS CloudFormation parameters, you can create multiple environments for your application from the same template\. [AWS SAM](gettingstarted-tools.md#gettingstarted-tools-awssam) extends AWS CloudFormation with a simplified syntax focused on Lambda application development\. - -The [AWS CLI](gettingstarted-tools.md#gettingstarted-tools-awscli) and [SAM CLI](gettingstarted-tools.md#gettingstarted-tools-samcli) are command line tools for managing Lambda application stacks\. In addition to commands for managing application stacks with the AWS CloudFormation API, the AWS CLI supports higher\-level commands that simplify tasks like uploading deployment packages and updating templates\. The AWS SAM CLI provides additional functionality, including validating templates and testing locally\. - -**Topics** -+ [Managing applications in the AWS Lambda console](applications-console.md) -+ [Creating an application with continuous delivery in the Lambda console](applications-tutorial.md) -+ [Rolling deployments for Lambda functions](lambda-rolling-deployments.md) -+ [Common Lambda application types and use cases](applications-usecases.md) -+ [Best Practices for Working with AWS Lambda Functions](best-practices.md) \ No newline at end of file diff --git a/doc_source/downstream-tracing.md b/doc_source/downstream-tracing.md deleted file mode 100644 index 6114cd3a..00000000 --- a/doc_source/downstream-tracing.md +++ /dev/null @@ -1,11 +0,0 @@ -# Emitting trace segments from a Lambda function - -For each traced invocation, Lambda will emit the Lambda service segment and all of its subsegments\. In addition, Lambda will emit the Lambda function segment and the init subsegment\. These segments will be emitted regardless of the function's runtime, and with no code changes or additional libraries required\. If you want your Lambda function's X\-Ray traces to include custom segments, annotations, or subsegments for downstream calls, you might need to include additional libraries and annotate your code\. - -Note that any instrumentation code must be implemented inside the Lambda function handler and not as part of the initialization code\. - -The following examples explain how to do this in the supported runtimes: -+ [Instrumenting Python code in AWS Lambda](python-tracing.md) -+ [Instrumenting Node\.js code in AWS Lambda](nodejs-tracing.md) -+ [Instrumenting Java code in AWS Lambda](java-tracing.md) -+ [Instrumenting Go code in AWS Lambda](golang-tracing.md) \ No newline at end of file diff --git a/doc_source/functions-states.md b/doc_source/functions-states.md deleted file mode 100644 index 8eb61de2..00000000 --- a/doc_source/functions-states.md +++ /dev/null @@ -1,73 +0,0 @@ -# Monitoring the state of a function with the Lambda API - -When you create or update a function, Lambda provisions the compute and networking resources that enable it to run\. In most cases, this process is very fast, and your function is ready to be invoked or modified right away\. - -If you configure your function to connect to a virtual private cloud \(VPC\), the process can take longer\. When you first connect a function to a VPC, Lambda provisions network interfaces, which takes about a minute\. To communicate the current state of your function, Lambda includes additional fields in the [function configuration](API_FunctionConfiguration.md) document that is returned by several Lambda API actions\. - -When you create a function, the function is initially in the `Pending` state\. When the function is ready to be invoked, the state changes from `Pending` to `Active`\. While the state is `Pending`, invocations and other API actions that operate on the function return an error\. If you build automation around creating and updating functions, wait for the function to become active before performing additional actions that operate on the function\. - -You can use the Lambda API to get information about a function's state\. State information is included in the [FunctionConfiguration](API_FunctionConfiguration.md) document returned by several API actions\. To view the function's state with the AWS CLI, use the `get-function-configuration` command\. - -``` -$ aws lambda get-function-configuration --function-name my-function -{ - "FunctionName": "my-function", - "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function", - "Runtime": "nodejs12.x", - "Role": "arn:aws:iam::123456789012:role/lambda-role", - "TracingConfig": { - "Mode": "Active" - }, - "State": "Pending", - "StateReason": "The function is being created.", - "StateReasonCode": "Creating", - ... -} -``` - -The `StateReason` and `StateReasonCode` contain additional information about the state when it is not `Active`\. The following operations fail while function creation is pending: -+ [Invoke](API_Invoke.md) -+ [UpdateFunctionCode](API_UpdateFunctionCode.md) -+ [UpdateFunctionConfiguration](API_UpdateFunctionConfiguration.md) -+ [PublishVersion](API_PublishVersion.md) - -When you update a function's configuration, the update can trigger an asynchronous operation to provision resources\. While this is in progress, you can invoke the function, but other operations on the function fail\. Invocations that occur while the update is in progress run against the previous configuration\. The function's state is `Active`, but its `LastUpdateStatus` is `InProgress`\. - -**Example Function configuration – Connecting to a VPC** - -``` -{ - "FunctionName": "my-function", - "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function", - "Runtime": "nodejs12.x", - "VpcConfig": { - "SubnetIds": [ - "subnet-071f712345678e7c8", - "subnet-07fd123456788a036", - "subnet-0804f77612345cacf" - ], - "SecurityGroupIds": [ - "sg-085912345678492fb" - ], - "VpcId": "vpc-08e1234569e011e83" - }, - "State": "Active", - "LastUpdateStatus": "InProgress", - ... -} -``` - -The following operations fail while an asynchronous update is in progress: -+ [UpdateFunctionCode](API_UpdateFunctionCode.md) -+ [UpdateFunctionConfiguration](API_UpdateFunctionConfiguration.md) -+ [PublishVersion](API_PublishVersion.md) - -Other operations, including invocation, work while updates are in progress\. - -For example, when you connect your function to a virtual private cloud \(VPC\), Lambda provisions an elastic network interface for each subnet\. This process can leave your function in a pending state for a minute or so\. Lambda also reclaims network interfaces that are not in use, placing your function in an `Inactive` state\. When the function is inactive, an invocation causes it to enter the `Pending` state while network access is restored\. The invocation that triggers restoration, and further invocations while the operation is pending, fail with `ResourceNotReadyException`\. - -If Lambda encounters an error when restoring a function's network interface, the function goes back to the `Inactive` state\. The next invocation can trigger another attempt\. For some configuration errors, Lambda waits at least 5 minutes before attempting to create another network interface\. These errors have the following `LastUpdateStatusReasonCode` values: -+ `InsufficientRolePermission` – Role doesn't exist or is missing permissions\. -+ `SubnetOutOfIPAddresses` – All IP addresses in a subnet are in use\. - -For more information on how states work with VPC connectivity, see [Configuring a Lambda function to access resources in a VPC](configuration-vpc.md)\. \ No newline at end of file diff --git a/doc_source/getting-started-create-function.md b/doc_source/getting-started-create-function.md deleted file mode 100644 index 417da61f..00000000 --- a/doc_source/getting-started-create-function.md +++ /dev/null @@ -1,97 +0,0 @@ -# Create a Lambda function with the console - -In this Getting Started exercise you create a Lambda function using the AWS Lambda console\. Next, you manually invoke the Lambda function using sample event data\. AWS Lambda executes the Lambda function and returns results\. You then verify execution results, including the logs that your Lambda function created and various CloudWatch metrics\. - -**To create a Lambda function** - -1. Open the [AWS Lambda console](https://console.aws.amazon.com/lambda/home)\. - -1. Choose **Create a function**\. - -1. For **Function name**, enter **my\-function**\. - -1. Choose **Create function**\. - -Lambda creates a Node\.js function and an execution role that grants the function permission to upload logs\. Lambda assumes the execution role when you invoke your function, and uses it to create credentials for the AWS SDK and to read data from event sources\. - -## Use the designer - -The **Designer** shows an overview of your function and its upstream and downstream resources\. You can use it to configure triggers, layers, and destinations\. - -![\[A Lambda function with an Amazon S3 trigger and Amazon EventBridge destination.\]](http://docs.aws.amazon.com/lambda/latest/dg/images/console-designer.png) - -Choose **my\-function** in the designer to return to the function's code and configuration\. For scripting languages, Lambda includes sample code that returns a success response\. You can edit your function code with the embedded [AWS Cloud9](https://docs.aws.amazon.com/cloud9/latest/user-guide/) editor as long as your source code doesn't exceed the 3 MB limit\. - -## Invoke the Lambda function - -Invoke your Lambda function using the sample event data provided in the console\. - -**To invoke a function** - -1. In the upper right corner, choose **Test**\. - -1. In the **Configure test event** page, choose **Create new test event** and in **Event template**, leave the default **Hello World** option\. Enter an **Event name** and note the following sample event template: - - ``` - { - "key3": "value3", - "key2": "value2", - "key1": "value1" - } - ``` - - You can change key and values in the sample JSON, but don't change the event structure\. If you do change any keys and values, you must update the sample code accordingly\. - -1. Choose **Create** and then choose **Test**\. Each user can create up to 10 test events per function\. Those test events are not available to other users\. - -1. AWS Lambda executes your function on your behalf\. The `handler` in your Lambda function receives and then processes the sample event\. - -1. Upon successful execution, view results in the console\. - + The **Execution result** section shows the execution status as **succeeded** and also shows the function execution results, returned by the `return` statement\. - + The **Summary** section shows the key information reported in the **Log output** section \(the *REPORT* line in the execution log\)\. - + The **Log output** section shows the log AWS Lambda generates for each execution\. These are the logs written to CloudWatch by the Lambda function\. The AWS Lambda console shows these logs for your convenience\. - - Note that the **Click here** link shows logs in the CloudWatch console\. The function then adds logs to Amazon CloudWatch in the log group that corresponds to the Lambda function\. - -1. Run the Lambda function a few times to gather some metrics that you can view in the next step\. - -1. Choose **Monitoring**\. This page shows graphs for the metrics that Lambda sends to CloudWatch\. -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/metrics-functions-list.png) - - For more information on these graphs, see [Monitoring functions in the AWS Lambda console](monitoring-functions-access-metrics.md)\. - -## Clean up - -If you are done working with the example function, delete it\. You can also delete the execution role that the console created, and the log group that stores the function's logs\. - -**To delete a Lambda function** - -1. Open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions)\. - -1. Choose a function\. - -1. Choose **Actions**, and then choose **Delete function**\. - -1. Choose **Delete**\. - -**To delete the log group** - -1. Open the [Log groups page](https://console.aws.amazon.com/cloudwatch/home#logs:) of the Amazon CloudWatch console\. - -1. Choose the function's log group \(`/aws/lambda/my-function`\)\. - -1. Choose **Actions**, and then choose **Delete log group**\. - -1. Choose **Yes, Delete**\. - -**To delete the execution role** - -1. Open the [Roles page](https://console.aws.amazon.com/iam/home?#/roles) of the AWS Identity and Access Management console\. - -1. Choose the function's role \(`my-function-role-31exxmpl` - -1. Choose **Delete role**\. - -1. Choose **Yes, delete**\. - -You can automate the creation and cleanup of functions, roles, and log groups with AWS CloudFormation and the AWS CLI\. For fully functional sample applications, see [Lambda sample applications](lambda-samples.md)\. \ No newline at end of file diff --git a/doc_source/getting-started.md b/doc_source/getting-started.md deleted file mode 100644 index 8511486f..00000000 --- a/doc_source/getting-started.md +++ /dev/null @@ -1,18 +0,0 @@ -# Getting started with AWS Lambda - -To get started with AWS Lambda, use the Lambda console to create a function\. In a few minutes, you can create a function, invoke it, and view logs, metrics, and trace data\. - -**Note** -To use Lambda and other AWS services, you need an AWS account\. If you don't have an account, visit [aws\.amazon\.com](https://aws.amazon.com/) and choose **Create an AWS Account**\. For detailed instructions, see [Create and activate an AWS account](https://aws.amazon.com/premiumsupport/knowledge-center/create-and-activate-aws-account/)\. -As a best practice, you should also create an AWS Identity and Access Management \(IAM\) user with administrator permissions and use that for all work that does not require root credentials\. Create a password for console access, and access keys to use command line tools\. See [Creating your first IAM admin user and group](https://docs.aws.amazon.com/IAM/latest/UserGuide/getting-started_create-admin-group.html) in the *IAM User Guide* for instructions\. - -You can author functions in the Lambda console—or with an IDE toolkit, command line tools, or SDKs\. The Lambda console provides a [code editor](code-editor.md) for noncompiled languages that lets you modify and test code quickly\. The [AWS CLI](gettingstarted-awscli.md) gives you direct access to the Lambda API for advanced configuration and automation use cases\. - -**Topics** -+ [Create a Lambda function with the console](getting-started-create-function.md) -+ [Creating functions using the AWS Lambda console editor](code-editor.md) -+ [Using AWS Lambda with the AWS Command Line Interface](gettingstarted-awscli.md) -+ [AWS Lambda concepts](gettingstarted-concepts.md) -+ [AWS Lambda features](gettingstarted-features.md) -+ [Tools for working with AWS Lambda](gettingstarted-tools.md) -+ [AWS Lambda limits](gettingstarted-limits.md) \ No newline at end of file diff --git a/doc_source/gettingstarted-awscli.md b/doc_source/gettingstarted-awscli.md deleted file mode 100644 index bf190cc7..00000000 --- a/doc_source/gettingstarted-awscli.md +++ /dev/null @@ -1,283 +0,0 @@ -# Using AWS Lambda with the AWS Command Line Interface - -You can use the AWS Command Line Interface to manage functions and other AWS Lambda resources\. The AWS CLI uses the AWS SDK for Python \(Boto\) to interact with the Lambda API\. You can use it to learn about the API, and apply that knowledge in building applications that use Lambda with the AWS SDK\. - -In this tutorial, you manage and invoke Lambda functions with the AWS CLI\. - -## Prerequisites - -This tutorial assumes that you have some knowledge of basic Lambda operations and the Lambda console\. If you haven't already, follow the instructions in [Getting started with AWS Lambda](getting-started.md) to create your first Lambda function\. - -To follow the procedures in this guide, you will need a command line terminal or shell to run commands\. Commands are shown in listings preceded by a prompt symbol \($\) and the name of the current directory, when appropriate: - -``` -~/lambda-project$ this is a command -this is output -``` - -For long commands, an escape character \(`\`\) is used to split a command over multiple lines\. - -On Linux and macOS, use your preferred shell and package manager\. On Windows 10, you can [install the Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows\-integrated version of Ubuntu and Bash\. - -This tutorial uses the AWS Command Line Interface \(AWS CLI\) to call service API operations\. To install the AWS CLI, see [Installing the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html) in the AWS Command Line Interface User Guide\. - -## Create the execution role - -Create the [execution role](lambda-intro-execution-role.md) that gives your function permission to access AWS resources\. To create an execution role with the AWS CLI, use the `create-role` command\. - -``` -$ aws iam create-role --role-name lambda-ex --assume-role-policy-document file://trust-policy.json -{ - "Role": { - "Path": "/", - "RoleName": "lambda-ex", - "RoleId": "AROAQFOXMPL6TZ6ITKWND", - "Arn": "arn:aws:iam::123456789012:role/lambda-ex", - "CreateDate": "2020-01-17T23:19:12Z", - "AssumeRolePolicyDocument": { - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Allow", - "Principal": { - "Service": "lambda.amazonaws.com" - }, - "Action": "sts:AssumeRole" - } - ] - } - } -} -``` - -The `trust-policy.json` file is a JSON file in the current directory that defines the [trust policy](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html) for the role\. This trust policy allows Lambda to use the role's permissions by giving the service principal `lambda.amazonaws.com` permission to call the AWS Security Token Service `AssumeRole` action\. - -**Example trust\-policy\.json** - -``` -{ - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Allow", - "Principal": { - "Service": "lambda.amazonaws.com" - }, - "Action": "sts:AssumeRole" - } - ] -} -``` - -You can also specify the trust policy inline\. Requirements for escaping quotes in the JSON string vary depending on your shell\. - -``` -$ aws iam create-role --role-name lambda-ex --assume-role-policy-document '{"Version": "2012-10-17","Statement": [{ "Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"}, "Action": "sts:AssumeRole"}]}' -``` - -To add permissions to the role, use the `attach-policy-to-role` command\. Start by adding the `AWSLambdaBasicExecutionRole` managed policy\. - -``` -$ aws iam attach-role-policy --role-name lambda-ex --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole -``` - -The **AWSLambdaBasicExecutionRole** policy has the permissions that the function needs to write logs to CloudWatch Logs\. - -## Create the function - -The following example logs the values of environment variables and the event object\. - -**Example index\.js** - -``` -exports.handler = async function(event, context) { - console.log("ENVIRONMENT VARIABLES\n" + JSON.stringify(process.env, null, 2)) - console.log("EVENT\n" + JSON.stringify(event, null, 2)) - return context.logStreamName -} -``` - -**To create the function** - -1. Copy the sample code into a file named `index.js`\. - -1. Create a deployment package\. - - ``` - $ zip function.zip index.js - ``` - -1. Create a Lambda function with the `create-function` command\. Replace the highlighted text in the role ARN with your account ID\. - - ``` - $ aws lambda create-function --function-name my-function \ - --zip-file fileb://function.zip --handler index.handler --runtime nodejs12.x \ - --role arn:aws:iam::123456789012:role/lambda-ex - { - "FunctionName": "my-function", - "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function", - "Runtime": "nodejs12.x", - "Role": "arn:aws:iam::123456789012:role/lambda-ex", - "Handler": "index.handler", - "CodeSha256": "FpFMvUhayLkOoVBpNuNiIVML/tuGv2iJQ7t0yWVTU8c=", - "Version": "$LATEST", - "TracingConfig": { - "Mode": "PassThrough" - }, - "RevisionId": "88ebe1e1-bfdf-4dc3-84de-3017268fa1ff", - ... - } - ``` - -To get logs for an invocation from the command line, use the `--log-type` option\. The response includes a `LogResult` field that contains up to 4 KB of base64\-encoded logs from the invocation\. - -``` -$ aws lambda invoke --function-name my-function out --log-type Tail -{ - "StatusCode": 200, - "LogResult": "U1RBUlQgUmVxdWVzdElkOiA4N2QwNDRiOC1mMTU0LTExZTgtOGNkYS0yOTc0YzVlNGZiMjEgVmVyc2lvb...", - "ExecutedVersion": "$LATEST" -} -``` - -You can use the `base64` utility to decode the logs\. - -``` -$ aws lambda invoke --function-name my-function out --log-type Tail \ ---query 'LogResult' --output text | base64 -d -START RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 Version: $LATEST - "AWS_SESSION_TOKEN": "AgoJb3JpZ2luX2VjELj...", "_X_AMZN_TRACE_ID": "Root=1-5d02e5ca-f5792818b6fe8368e5b51d50;Parent=191db58857df8395;Sampled=0"",ask/lib:/opt/lib", -END RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 -REPORT RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 Duration: 79.67 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 73 MB -``` - -The `base64` utility is available on Linux, macOS, and [Ubuntu on Windows](https://docs.microsoft.com/en-us/windows/wsl/install-win10)\. For macOS, the command is `base64 -D`\. - -To get full log events from the command line, you can include the log stream name in the output of your function, as shown in the preceding example\. The following example script invokes a function named `my-function` and downloads the last five log events\. - -**Example get\-logs\.sh Script** -This example requires that `my-function` returns a log stream ID\. - -``` -#!/bin/bash -aws lambda invoke --function-name my-function --payload '{"key": "value"}' out -sed -i'' -e 's/"//g' out -sleep 15 -aws logs get-log-events --log-group-name /aws/lambda/my-function --log-stream-name $(cat out) --limit 5 -``` - -The script uses `sed` to remove quotes from the output file, and sleeps for 15 seconds to allow time for the logs to be available\. The output includes the response from Lambda and the output from the `get-log-events` command\. - -``` -$ ./get-logs.sh -{ - "StatusCode": 200, - "ExecutedVersion": "$LATEST" -} -{ - "events": [ - { - "timestamp": 1559763003171, - "message": "START RequestId: 4ce9340a-b765-490f-ad8a-02ab3415e2bf Version: $LATEST\n", - "ingestionTime": 1559763003309 - }, - { - "timestamp": 1559763003173, - "message": "2019-06-05T19:30:03.173Z\t4ce9340a-b765-490f-ad8a-02ab3415e2bf\tINFO\tENVIRONMENT VARIABLES\r{\r \"AWS_LAMBDA_FUNCTION_VERSION\": \"$LATEST\",\r ...", - "ingestionTime": 1559763018353 - }, - { - "timestamp": 1559763003173, - "message": "2019-06-05T19:30:03.173Z\t4ce9340a-b765-490f-ad8a-02ab3415e2bf\tINFO\tEVENT\r{\r \"key\": \"value\"\r}\n", - "ingestionTime": 1559763018353 - }, - { - "timestamp": 1559763003218, - "message": "END RequestId: 4ce9340a-b765-490f-ad8a-02ab3415e2bf\n", - "ingestionTime": 1559763018353 - }, - { - "timestamp": 1559763003218, - "message": "REPORT RequestId: 4ce9340a-b765-490f-ad8a-02ab3415e2bf\tDuration: 26.73 ms\tBilled Duration: 100 ms \tMemory Size: 128 MB\tMax Memory Used: 75 MB\t\n", - "ingestionTime": 1559763018353 - } - ], - "nextForwardToken": "f/34783877304859518393868359594929986069206639495374241795", - "nextBackwardToken": "b/34783877303811383369537420289090800615709599058929582080" -} -``` - -## List the Lambda functions in your account - -Execute the following AWS CLI `list-functions` command to retrieve a list of functions that you have created\. - -``` -$ aws lambda list-functions --max-items 10 -{ - "Functions": [ - { - "FunctionName": "cli", - "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function", - "Runtime": "nodejs12.x", - "Role": "arn:aws:iam::123456789012:role/lambda-ex", - "Handler": "index.handler", - ... - }, - { - "FunctionName": "random-error", - "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:random-error", - "Runtime": "nodejs12.x", - "Role": "arn:aws:iam::123456789012:role/lambda-role", - "Handler": "index.handler", - ... - }, - ... - ], - "NextToken": "eyJNYXJrZXIiOiBudWxsLCAiYm90b190cnVuY2F0ZV9hbW91bnQiOiAxMH0=" -} -``` - -In response, Lambda returns a list of up to 10 functions\. If there are more functions you can retrieve, `NextToken` provides a marker you can use in the next `list-functions` request\. The following `list-functions` AWS CLI command is an example that shows the `--starting-token` parameter\. - -``` -$ aws lambda list-functions --max-items 10 --starting-token eyJNYXJrZXIiOiBudWxsLCAiYm90b190cnVuY2F0ZV9hbW91bnQiOiAxMH0= -``` - -## Retrieve a Lambda function - -The Lambda CLI `get-function` command returns Lambda function metadata and a presigned URL that you can use to download the function's deployment package\. - -``` -$ aws lambda get-function --function-name my-function -{ - "Configuration": { - "FunctionName": "my-function", - "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function", - "Runtime": "nodejs12.x", - "Role": "arn:aws:iam::123456789012:role/lambda-ex", - "CodeSha256": "FpFMvUhayLkOoVBpNuNiIVML/tuGv2iJQ7t0yWVTU8c=", - "Version": "$LATEST", - "TracingConfig": { - "Mode": "PassThrough" - }, - "RevisionId": "88ebe1e1-bfdf-4dc3-84de-3017268fa1ff", - ... - }, - "Code": { - "RepositoryType": "S3", - "Location": "https://awslambda-us-east-2-tasks.s3.us-east-2.amazonaws.com/snapshots/123456789012/my-function-4203078a-b7c9-4f35-..." - } -} -``` - -For more information, see [GetFunction](API_GetFunction.md)\. - -## Clean up - -Execute the following `delete-function` command to delete the `my-function` function\. - -``` -$ aws lambda delete-function --function-name my-function -``` - -Delete the IAM role you created in the IAM console\. For information about deleting a role, see [Deleting roles or instance profiles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_manage_delete.html) in the *IAM User Guide*\. \ No newline at end of file diff --git a/doc_source/gettingstarted-concepts.md b/doc_source/gettingstarted-concepts.md deleted file mode 100644 index b853b7e7..00000000 --- a/doc_source/gettingstarted-concepts.md +++ /dev/null @@ -1,67 +0,0 @@ -# AWS Lambda concepts - -With AWS Lambda, you run functions to process events\. You can send events to your function by invoking it with the Lambda API, or by configuring an AWS service or resource to invoke it\. - -**Topics** -+ [Function](#gettingstarted-concepts-function) -+ [Runtime](#gettingstarted-concepts-runtimes) -+ [Event](#gettingstarted-concepts-event) -+ [Concurrency](#gettingstarted-concepts-concurrency) -+ [Trigger](#gettingstarted-concepts-trigger) - -## Function - -A function is a resource that you can invoke to run your code in AWS Lambda\. A function has code that processes events, and a runtime that passes requests and responses between Lambda and the function code\. You provide the code, and you can use the provided runtimes or create your own\. - -For more information, see [Managing AWS Lambda functions](lambda-functions.md)\. - -## Runtime - -Lambda runtimes allow functions in different languages to run in the same base execution environment\. You configure your function to use a runtime that matches your programming language\. The runtime sits in between the Lambda service and your function code, relaying invocation events, context information, and responses between the two\. You can use runtimes provided by Lambda, or build your own\. - -For more information, see [AWS Lambda runtimes](lambda-runtimes.md)\. - -## Event - -An event is a JSON formatted document that contains data for a function to process\. The Lambda runtime converts the event to an object and passes it to your function code\. When you invoke a function, you determine the structure and contents of the event\. - -**Example Custom event – Weather data** - -``` -{ - "TemperatureK": 281, - "WindKmh": -3, - "HumidityPct": 0.55, - "PressureHPa": 1020 -} -``` - -When an AWS service invokes your function, the service defines the shape of the event\. - -**Example Service event – Amazon SNS notification** - -``` -{ - "Records": [ - { - "Sns": { - "Timestamp": "2019-01-02T12:45:07.000Z", - "Signature": "tcc6faL2yUC6dgZdmrwh1Y4cGa/ebXEkAi6RibDsvpi+tE/1+82j...65r==", - "MessageId": "95df01b4-ee98-5cb9-9903-4c221d41eb5e", - "Message": "Hello from SNS!", - ... -``` - -For details on events from AWS services, see [Using AWS Lambda with other services](lambda-services.md)\. - -## Concurrency - -Concurrency is the number of requests that your function is serving at any given time\. When your function is invoked, Lambda provisions an instance of it to process the event\. When the function code finishes running, it can handle another request\. If the function is invoked again while a request is still being processed, another instance is provisioned, increasing the function's concurrency\. - -Concurrency is subject to limits at the region level\. You can also configure individual functions to limit their concurrency, or to ensure that they can reach a specific level of concurrency\. For more information, see [Managing concurrency for a Lambda function](configuration-concurrency.md)\. - -## Trigger - -A trigger is a resource or configuration that invokes a Lambda function\. This includes AWS services that can be configured to invoke a function, applications that you develop, and event source mappings\. An event source mapping is a resource in Lambda that reads items from a stream or queue and invokes a function\. - -For more information, see [Invoking AWS Lambda functions](lambda-invocation.md) and [Using AWS Lambda with other services](lambda-services.md)\. \ No newline at end of file diff --git a/doc_source/gettingstarted-features.md b/doc_source/gettingstarted-features.md deleted file mode 100644 index 90e77062..00000000 --- a/doc_source/gettingstarted-features.md +++ /dev/null @@ -1,126 +0,0 @@ -# AWS Lambda features - -AWS Lambda provides a management console and API for managing and invoking functions\. It provides runtimes that support a standard set of features so that you can easily switch between languages and frameworks, depending on your needs\. In addition to functions, you can also create versions, aliases, layers, and custom runtimes\. - -**Topics** -+ [Programming model](#gettingstarted-features-programmingmodel) -+ [Deployment package](#gettingstarted-features-package) -+ [Layers](#gettingstarted-features-layers) -+ [Scaling](#gettingstarted-features-scaling) -+ [Concurrency controls](#gettingstarted-features-concurrency) -+ [Asynchronous invocation](#gettingstarted-features-async) -+ [Event source mappings](#gettingstarted-features-eventsourcemapping) -+ [Destinations](#gettingstarted-features-destinations) -+ [Function blueprints](#gettingstarted-features-blueprints) -+ [Application templates](#gettingstarted-features-templates) - -## Programming model - -Authoring specifics vary between runtimes, but all runtimes share a common programming model that defines the interface between your code and the runtime code\. You tell the runtime which method to run by defining a **handler** in the function configuration, and the runtime runs that method\. The runtime passes in objects to the handler that contain the invocation **event** and the **context**, such as the function name and request ID\. - -When the handler finishes processing the first event, the runtime sends it another\. The function's class stays in memory, so clients and variables that are declared outside of the handler method in **initialization code** can be reused\. To save processing time on subsequent events, create reusable resources like AWS SDK clients during initialization\. Once initialized, each instance of your function can process thousands of requests\. - -Initialization is billed as part of the duration for the first invocation processed by an instance of your function\. When [X\-Ray tracing](lambda-x-ray.md) is enabled, the runtime records separate subsegments for initialization and execution\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-initialization-trace.png) - -Your function also has access to local storage in the `/tmp` directory\. Instances of your function that are serving requests remain active for a few hours before being recycled\. - -The runtime captures **logging** output from your function and sends it to Amazon CloudWatch Logs\. In addition to logging your function's output, the runtime also logs entries when execution starts and ends\. This includes a report log with the request ID, billed duration, initialization duration, and other details\. If your function throws an **error**, the runtime returns that error to the invoker\. - -**Note** -Logging is subject to [CloudWatch Logs limits](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/cloudwatch_limits_cwl.html)\. Log data can be lost due to throttling or, in some cases, when an instance of your function is stopped\. - -For a hands\-on introduction to the programming model in your preferred programming language, see the following chapters\. -+ [Building Lambda functions with Node\.js](lambda-nodejs.md) -+ [Building Lambda functions with Python](lambda-python.md) -+ [Building Lambda functions with Ruby](lambda-ruby.md) -+ [Building Lambda functions with Java](lambda-java.md) -+ [Building Lambda functions with Go](lambda-golang.md) -+ [Building Lambda functions with C\#](lambda-csharp.md) -+ [Building Lambda functions with PowerShell](lambda-powershell.md) - -Lambda scales your function by running additional instances of it as demand increases, and by stopping instances as demand decreases\. Unless noted otherwise, incoming requests might be processed out of order or concurrently\. Store your application's state in other services, and don't rely on instances of your function being long lived\. Use local storage and class\-level objects to increase performance, but keep the size of your deployment package and the amount of data that you transfer onto the execution environment to a minimum\. - -## Deployment package - -Your function's code consists of scripts or compiled programs and their dependencies\. When you author functions in the Lambda console or a toolkit, the client creates a ZIP archive of your code called a deployment package\. The client then sends the package to the Lambda service\. When you manage functions with the Lambda API, command line tools, or SDKs, you create the deployment package\. You also need to create a deployment package manually for compiled languages and to add dependencies to your function\. - -For language\-specific instructions, see the following topics\. -+ [AWS Lambda deployment package in Node\.js](nodejs-package.md) -+ [AWS Lambda deployment package in Python](python-package.md) -+ [AWS Lambda deployment package in Ruby](ruby-package.md) -+ [AWS Lambda deployment package in Java](java-package.md) -+ [AWS Lambda deployment package in Go](golang-package.md) -+ [AWS Lambda Deployment Package in C\#](csharp-package.md) -+ [AWS Lambda deployment package in PowerShell](powershell-package.md) - -## Layers - -Lambda layers are a distribution mechanism for libraries, custom runtimes, and other function dependencies\. Layers let you manage your in\-development function code independently from the unchanging code and resources that it uses\. You can configure your function to use layers that you create, layers provided by AWS, or layers from other AWS customers\. - -For more information, see [AWS Lambda layers](configuration-layers.md)\. - -## Scaling - -Lambda manages the infrastructure that runs your code, and scales automatically in response to incoming requests\. When your function is invoked more quickly than a single instance of your function can process events, Lambda scales up by running additional instances\. When traffic subsides, inactive instances are frozen or stopped\. You only pay for the time that your function is initializing or processing events\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-scaling.png) - -For more information, see [AWS Lambda function scaling](invocation-scaling.md)\. - -## Concurrency controls - -Use concurrency settings to ensure that your production applications are highly available and highly responsive\. To prevent a function from using too much concurrency, and to reserve a portion of your account's available concurrency for a function, use *reserved concurrency*\. Reserved concurrency splits the pool of available concurrency into subsets\. A function with reserved concurrency only uses concurrency from its dedicated pool\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-concurrency-reserved.png) - -To enable functions to scale without fluctuations in latency, use *provisioned concurrency*\. For functions that take a long time to initialize, or require extremely low latency for all invocations, provisioned concurrency enables you to pre\-initialize instances of your function and keep them running at all times\. Lambda integrates with Application Auto Scaling to support autoscaling for provisioned concurrency based on utilization\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-scaling-provisioned-auto.png) - -For more information, see [Managing concurrency for a Lambda function](configuration-concurrency.md)\. - -## Asynchronous invocation - -When you invoke a function, you can choose to invoke it synchronously or asynchronously\. With [synchronous invocation](invocation-sync.md), you wait for the function to process the event and return a response\. With asynchronous invocation, Lambda queues the event for processing and returns a response immediately\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-async.png) - -For asynchronous invocations, Lambda handles retries if the function returns an error or is throttled\. To customize this behavior, you can configure error handling settings on a function, version, or alias\. You can also configure Lambda to send events that failed processing to a dead\-letter queue, or to send a record of any invocation to a [destination](#gettingstarted-features-destinations)\. - -For more information, see [Asynchronous invocation](invocation-async.md)\. - -## Event source mappings - -To process items from a stream or queue, you can create an [event source mapping](invocation-eventsourcemapping.md)\. An event source mapping is a resource in Lambda that reads items from an Amazon SQS queue, an Amazon Kinesis stream, or an Amazon DynamoDB stream, and sends them to your function in batches\. Each event that your function processes can contain hundreds or thousands of items\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-eventsourcemapping.png) - -Event source mappings maintain a local queue of unprocessed items, and handle retries if the function returns an error or is throttled\. You can configure an event source mapping to customize batching behavior and error handling, or to send a record of items that fail processing to a [destination](#gettingstarted-features-destinations)\. - -For more information, see [AWS Lambda event source mappings](invocation-eventsourcemapping.md)\. - -## Destinations - -A destination is an AWS resource that receives invocation records for a function\. For [asynchronous invocation](#gettingstarted-features-async), you can configure Lambda to send invocation records to a queue, topic, function, or event bus\. You can configure separate destinations for successful invocations and events that failed processing\. The invocation record contains details about the event, the function's response, and the reason that the record was sent\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-destinations.png) - -For [event source mappings](#gettingstarted-features-eventsourcemapping) that read from streams, you can configure Lambda to send a record of batches that failed processing to a queue or topic\. A failure record for an event source mapping contains metadata about the batch, and it points to the items in the stream\. - -For more information, see [Configuring destinations for asynchronous invocation](invocation-async.md#invocation-async-destinations) and the error handling sections of [Using AWS Lambda with Amazon DynamoDB](with-ddb.md) and [Using AWS Lambda with Amazon Kinesis](with-kinesis.md)\. - -## Function blueprints - -When you create a function in the Lambda console, you can choose to start from scratch, use a blueprint, or deploy an application from the [AWS Serverless Application Repository](https://docs.aws.amazon.com/serverlessrepo/latest/devguide/what-is-serverlessrepo.html)\. A blueprint provides sample code that shows how to use Lambda with an AWS service or a popular third\-party application\. Blueprints include sample code and function configuration presets for Node\.js and Python runtimes\. - -Blueprints are provided for use under the [Creative Commons Zero](https://spdx.org/licenses/CC0-1.0.html) license\. They are only available in the Lambda console\. - -## Application templates - -You can use the Lambda console to create an application with a continuous delivery pipeline\. Application templates in the Lambda console include code for one or more functions, an application template that defines functions and supporting AWS resources, and an infrastructure template that defines an AWS CodePipeline pipeline\. The pipeline has build and deploy stages that run every time you push changes to the included Git repository\. - -Application templates are provided for use under the [MIT No Attribution](https://spdx.org/licenses/MIT-0.html) license\. They are only available in the Lambda console\. - -For more information, see [Creating an application with continuous delivery in the Lambda console](applications-tutorial.md)\. \ No newline at end of file diff --git a/doc_source/gettingstarted-limits.md b/doc_source/gettingstarted-limits.md deleted file mode 100644 index 6a0bbc99..00000000 --- a/doc_source/gettingstarted-limits.md +++ /dev/null @@ -1,34 +0,0 @@ -# AWS Lambda limits - -AWS Lambda limits the amount of compute and storage resources that you can use to run and store functions\. The following limits apply per\-region and can be increased\. To request an increase, use the [Support Center console](https://console.aws.amazon.com/support/v1#/case/create?issueType=service-limit-increase)\. - - -| Resource | Default limit | -| --- | --- | -| Concurrent executions | 1,000 | -| Function and layer storage | 75 GB | -| [Elastic network interfaces per VPC](configuration-vpc.md) | 250 | - -For details on concurrency and how Lambda scales your function concurrency in response to traffic, see [AWS Lambda function scaling](invocation-scaling.md)\. - -The following limits apply to function configuration, deployments, and execution\. They cannot be changed\. - - -| Resource | Limit | -| --- | --- | -| Function [memory allocation](configuration-console.md) | 128 MB to 3,008 MB, in 64 MB increments\. | -| Function [timeout](configuration-console.md) | 900 seconds \(15 minutes\) | -| Function [environment variables](configuration-envvars.md) | 4 KB | -| Function [resource\-based policy](access-control-resource-based.md) | 20 KB | -| Function [layers](configuration-layers.md) | 5 layers | -| Function [burst concurrency](invocation-scaling.md) | 500 \- 3000 \([varies per region](invocation-scaling.md)\) | -| Invocation frequency per Region \(requests per second\) | 10 x concurrent executions limit \([synchronous](invocation-sync.md) – all sources\) 10 x concurrent executions limit \([asynchronous](invocation-async.md) – non\-AWS sources\) Unlimited \(asynchronous – [AWS service sources](lambda-services.md)\) | -| Invocation frequency per function version or alias \(requests per second\) | 10 x allocated [provisioned concurrency](configuration-concurrency.md) This limit only applies to functions that use provisioned concurrency\. | -| [Invocation payload](lambda-invocation.md) \(request and response\) | 6 MB \(synchronous\) 256 KB \(asynchronous\) | -| [Deployment package](gettingstarted-features.md#gettingstarted-features-package) size | 50 MB \(zipped, for direct upload\) 250 MB \(unzipped, including layers\) 3 MB \(console editor\) | -| Test events \(console editor\) | 10 | -| `/tmp` directory storage | 512 MB | -| File descriptors | 1,024 | -| Execution processes/threads | 1,024 | - -Limits for other services, such as AWS Identity and Access Management, Amazon CloudFront \(Lambda@Edge\), and Amazon Virtual Private Cloud, can impact your Lambda functions\. For more information, see [AWS service limits](https://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html) and [Using AWS Lambda with other services](lambda-services.md)\. \ No newline at end of file diff --git a/doc_source/gettingstarted-tools.md b/doc_source/gettingstarted-tools.md deleted file mode 100644 index 66ac099e..00000000 --- a/doc_source/gettingstarted-tools.md +++ /dev/null @@ -1,56 +0,0 @@ -# Tools for working with AWS Lambda - -In addition to the Lambda console, you can use the following tools to manage and invoke Lambda resources\. - -**Topics** -+ [AWS Command Line Interface](#gettingstarted-tools-awscli) -+ [AWS Serverless Application Model](#gettingstarted-tools-awssam) -+ [SAM CLI](#gettingstarted-tools-samcli) -+ [Code authoring tools](#lambda-app-author) - -## AWS Command Line Interface - -Install the AWS Command Line Interface to manage and use Lambda functions from the command line\. Tutorials in this guide use the AWS CLI, which has commands for all Lambda API actions\. Some functionality is not available in the Lambda console and can only be accessed with the AWS CLI or the AWS SDK\. - -To set up the AWS CLI, see the following topics in the *AWS Command Line Interface User Guide*\. -+ [Getting set up with the AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-set-up.html) -+ [Configuring the AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html) - -To verify that the AWS CLI is configured correctly, run the `list-functions` command to see a list of your Lambda functions in the current region\. - -``` -$ aws lambda list-functions -``` - -## AWS Serverless Application Model - -AWS SAM is an extension for the AWS CloudFormation template language that lets you define serverless applications at a higher level\. It abstracts away common tasks such as function role creation, which makes it easier to write templates\. AWS SAM is supported directly by AWS CloudFormation, and includes additional functionality through the AWS CLI and AWS SAM CLI\. - -For more information about AWS SAM templates, see [ AWS SAM template basics](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-template-basics.html) in the *AWS Serverless Application Model Developer Guide*\. - -## SAM CLI - -The AWS SAM CLI is a separate command line tool that you can use to manage and test AWS SAM applications\. In addition to commands for uploading artifacts and launching AWS CloudFormation stacks that are also available in the AWS CLI, the SAM CLI provides additional commands for validating templates and running applications locally in a Docker container\. - -To set up the AWS SAM CLI, see [Installing the AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) in the *AWS Serverless Application Model Developer Guide*\. - -## Code authoring tools - -You can author your Lambda function code in the languages that are supported by AWS Lambda\. For a list of supported languages, see [AWS Lambda runtimes](lambda-runtimes.md)\. There are tools for authoring code, such as the AWS Lambda console, Eclipse IDE, and Visual Studio IDE\. But the available tools and options depend on the following: -+ Language you choose to write your Lambda function code\. -+ Libraries that you use in your code\. AWS Lambda runtime provides some of the libraries and you must upload any additional libraries that you use\. - -The following table lists languages, and the available tools and options that you can use\. - - -**** - -| Language | Tools and options for authoring code | -| --- | --- | -| Node\.js | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-tools.html) | -| Java | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-tools.html) | -| C\# | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-tools.html) | -| Python | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-tools.html) | -| Ruby | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-tools.html) | -| Go | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-tools.html) | -| PowerShell | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-tools.html) | \ No newline at end of file diff --git a/doc_source/glossary.md b/doc_source/glossary.md deleted file mode 100644 index 0fccc48a..00000000 --- a/doc_source/glossary.md +++ /dev/null @@ -1,3 +0,0 @@ -# AWS glossary - -For the latest AWS terminology, see the [AWS glossary](https://docs.aws.amazon.com/general/latest/gr/glos-chap.html) in the *AWS General Reference*\. \ No newline at end of file diff --git a/doc_source/golang-context.md b/doc_source/golang-context.md deleted file mode 100644 index 997387d5..00000000 --- a/doc_source/golang-context.md +++ /dev/null @@ -1,84 +0,0 @@ -# AWS Lambda context object in Go - -When Lambda runs your function, it passes a context object to the [handler](golang-handler.md)\. This object provides methods and properties with information about the invocation, function, and execution environment\. - -The Lambda context library provides the following global variables, methods, and properties\. - -**Global variables** -+ `FunctionName` – The name of the Lambda function\. -+ `FunctionVersion` – The [version](configuration-versions.md) of the function\. -+ `MemoryLimitInMB` – The amount of memory that's allocated for the function\. -+ `LogGroupName` – The log group for the function\. -+ `LogStreamName` – The log stream for the function instance\. - -**Context methods** -+ `Deadline` – Returns the date that the execution times out, in Unix time milliseconds\. - -**Context properties** -+ `InvokedFunctionArn` – The Amazon Resource Name \(ARN\) that's used to invoke the function\. Indicates if the invoker specified a version number or alias\. -+ `AwsRequestID` – The identifier of the invocation request\. -+ `Identity` – \(mobile apps\) Information about the Amazon Cognito identity that authorized the request\. -+ `ClientContext` – \(mobile apps\) Client context that's provided to Lambda by the client application\. - -## Accessing invoke context information - -Lambda functions have access to metadata about their environment and the invocation request\. This can be accessed at [Package context](https://golang.org/pkg/context/)\. Should your handler include `context.Context` as a parameter, Lambda will insert information about your function into the context's `Value` property\. Note that you need to import the `lambdacontext` library to access the contents of the `context.Context` object\. - -``` -package main - -import ( - "context" - "log" - "github.com/aws/aws-lambda-go/lambda" - "github.com/aws/aws-lambda-go/lambdacontext" -) - -func CognitoHandler(ctx context.Context) { - lc, _ := lambdacontext.FromContext(ctx) - log.Print(lc.Identity.CognitoIdentityPoolID) -} - -func main() { - lambda.Start(CognitoHandler) -} -``` - -In the example above, `lc` is the variable used to consume the information that the context object captured and `log.Print(lc.Identity.CognitoIdentityPoolID)` prints that information, in this case, the CognitoIdentityPoolID\. - -The following example introduces how to use the context object to monitor how long it takes to execute your Lambda function\. This allows you to analyze performance expectations and adjust your function code accordingly, if needed\. - -``` -package main - -import ( - "context" - "log" - "time" - "github.com/aws/aws-lambda-go/lambda" -) - -func LongRunningHandler(ctx context.Context) (string, error) { - - deadline, _ := ctx.Deadline() - deadline = deadline.Add(-100 * time.Millisecond) - timeoutChannel := time.After(time.Until(deadline)) - - for { - - select { - - case <- timeoutChannel: - return "Finished before timing out.", nil - - default: - log.Print("hello!") - time.Sleep(50 * time.Millisecond) - } - } -} - -func main() { - lambda.Start(LongRunningHandler) -} -``` \ No newline at end of file diff --git a/doc_source/golang-envvars.md b/doc_source/golang-envvars.md deleted file mode 100644 index d7cbc73f..00000000 --- a/doc_source/golang-envvars.md +++ /dev/null @@ -1,22 +0,0 @@ -# Using environment variables - -To access [environment variables](configuration-envvars.md) in Go, use the [Getenv](https://golang.org/pkg/os/#Getenv) function\. - -The following explains how to do this\. Note that the function imports the [fmt](https://golang.org/pkg/fmt/) package to format the printed results and the [os](https://golang.org/pkg/os/) package, a platform\-independent system interface that allows you to access environment variables\. - -``` -package main - -import ( - "fmt" - "os" - "github.com/aws/aws-lambda-go/lambda" -) - -func main() { - fmt.Printf("%s is %s. years old\n", os.Getenv("NAME"), os.Getenv("AGE")) - -} -``` - -For a list of environment variables that are set by the Lambda runtime, see [Runtime environment variables](configuration-envvars.md#configuration-envvars-runtime)\. \ No newline at end of file diff --git a/doc_source/golang-exceptions.md b/doc_source/golang-exceptions.md deleted file mode 100644 index b2af9e95..00000000 --- a/doc_source/golang-exceptions.md +++ /dev/null @@ -1,31 +0,0 @@ -# AWS Lambda function errors in Go - -You can create custom error handling to raise an exception directly from your Lambda function and handle it directly\. - -The following code samples demonstrate how to do this\. Note that custom errors in Go must import the `errors` module\. - -``` -package main - -import ( - "errors" - "github.com/aws/aws-lambda-go/lambda" -) - -func OnlyErrors() error { - return errors.New("something went wrong!") -} - -func main() { - lambda.Start(OnlyErrors) -} -``` - -Which returns the following: - -``` -{ - "errorMessage": "something went wrong!", - "errorType": "errorString" -} -``` \ No newline at end of file diff --git a/doc_source/golang-handler.md b/doc_source/golang-handler.md deleted file mode 100644 index 116c991b..00000000 --- a/doc_source/golang-handler.md +++ /dev/null @@ -1,177 +0,0 @@ -# AWS Lambda function handler in Go - -A Lambda function written in [Go](https://golang.org/) is authored as a Go executable\. In your Lambda function code, you need to include the [github\.com/aws/aws\-lambda\-go/lambda](https://github.com/aws/aws-lambda-go/tree/master/lambda) package, which implements the Lambda programming model for Go\. In addition, you need to implement handler function code and a `main()` function\. - -``` -package main - -import ( - "fmt" - "context" - "github.com/aws/aws-lambda-go/lambda" -) - -type MyEvent struct { - Name string `json:"name"` -} - -func HandleRequest(ctx context.Context, name MyEvent) (string, error) { - return fmt.Sprintf("Hello %s!", name.Name ), nil -} - -func main() { - lambda.Start(HandleRequest) -} -``` - -Note the following: -+ **package main**: In Go, the package containing `func main()` must always be named `main`\. -+ **import**: Use this to include the libraries your Lambda function requires\. In this instance, it includes: - + **context: **[AWS Lambda context object in Go](golang-context.md)\. - + **fmt:** The Go [Formatting](https://golang.org/pkg/fmt/) object used to format the return value of your function\. - + **github\.com/aws/aws\-lambda\-go/lambda:** As mentioned previously, implements the Lambda programming model for Go\. -+ **func HandleRequest\(ctx context\.Context, name MyEvent\) \(string, error\)**: This is your Lambda handler signature and includes the code which will be executed\. In addition, the parameters included denote the following: - + **ctx context\.Context**: Provides runtime information for your Lambda function invocation\. `ctx` is the variable you declare to leverage the information available via [AWS Lambda context object in Go](golang-context.md)\. - + **name MyEvent**: An input type with a variable name of `name` whose value will be returned in the `return` statement\. - + **string, error**: Returns two values: string for success and standard [error](https://golang.org/pkg/builtin/#error) information\. For more information on custom error handling, see [AWS Lambda function errors in Go](golang-exceptions.md)\. - + **return fmt\.Sprintf\("Hello %s\!", name\), nil**: Simply returns a formatted "Hello" greeting with the name you supplied in the input event\. `nil` indicates there were no errors and the function executed successfully\. -+ **func main\(\)**: The entry point that executes your Lambda function code\. This is required\. - - By adding `lambda.Start(HandleRequest)` between `func main(){}` code brackets, your Lambda function will be executed\. Per Go language standards, the opening bracket, `{` must be placed directly at end the of the `main` function signature\. - -## Lambda function handler using structured types - -In the example above, the input type was a simple string\. But you can also pass in structured events to your function handler: - -``` -package main - -import ( - "fmt" - "github.com/aws/aws-lambda-go/lambda" -) - -type MyEvent struct { - Name string `json:"What is your name?"` - Age int `json:"How old are you?"` -} - -type MyResponse struct { - Message string `json:"Answer:"` -} - -func HandleLambdaEvent(event MyEvent) (MyResponse, error) { - return MyResponse{Message: fmt.Sprintf("%s is %d years old!", event.Name, event.Age)}, nil -} - -func main() { - lambda.Start(HandleLambdaEvent) -} -``` - -Your request would then look like this: - -``` -# request -{ - "What is your name?": "Jim", - "How old are you?": 33 -} -``` - -And the response would look like this: - -``` -# response -{ - "Answer": "Jim is 33 years old!" -} -``` - -To be exported, field names in the event struct must be capitalized\. For more information on handling events from AWS event sources, see [aws\-lambda\-go/events](https://github.com/aws/aws-lambda-go/tree/master/events)\. - -### Valid handler signatures - -You have several options when building a Lambda function handler in Go, but you must adhere to the following rules: -+ The handler must be a function\. -+ The handler may take between 0 and 2 arguments\. If there are two arguments, the first argument must implement `context.Context`\. -+ The handler may return between 0 and 2 arguments\. If there is a single return value, it must implement `error`\. If there are two return values, the second value must implement `error`\. For more information on implementing error\-handling information, see [AWS Lambda function errors in Go](golang-exceptions.md)\. - -The following lists valid handler signatures\. `TIn` and `TOut` represent types compatible with the *encoding/json* standard library\. For more information, see [func Unmarshal](https://golang.org/pkg/encoding/json/#Unmarshal) to learn how these types are deserialized\. -+ - - ``` - func () - ``` -+ - - ``` - func () error - ``` -+ - - ``` - func (TIn), error - ``` -+ - - ``` - func () (TOut, error) - ``` -+ - - ``` - func (context.Context) error - ``` -+ - - ``` - func (context.Context, TIn) error - ``` -+ - - ``` - func (context.Context) (TOut, error) - ``` -+ - - ``` - func (context.Context, TIn) (TOut, error) - ``` - -## Using global state - -You can declare and modify global variables that are independent of your Lambda function's handler code\. In addition, your handler may declare an `init` function that is executed when your handler is loaded\. This behaves the same in AWS Lambda as it does in standard Go programs\. A single instance of your Lambda function will never handle multiple events simultaneously\. - -``` -package main - -import ( - "log" - "github.com/aws/aws-lambda-go/lambda" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/aws" -) - -var invokeCount = 0 -var myObjects []*s3.Object -func init() { - svc := s3.New(session.New()) - input := &s3.ListObjectsV2Input{ - Bucket: aws.String("examplebucket"), - } - result, _ := svc.ListObjectsV2(input) - myObjects = result.Contents -} - -func LambdaHandler() (int, error) { - invokeCount = invokeCount + 1 - log.Print(myObjects) - return invokeCount, nil -} - -func main() { - lambda.Start(LambdaHandler) -} -``` \ No newline at end of file diff --git a/doc_source/golang-logging.md b/doc_source/golang-logging.md deleted file mode 100644 index 58c386a9..00000000 --- a/doc_source/golang-logging.md +++ /dev/null @@ -1,167 +0,0 @@ -# AWS Lambda function logging in Go - -Your Lambda function comes with a CloudWatch Logs log group, with a log stream for each instance of your function\. The runtime sends details about each invocation to the log stream, and relays logs and other output from your function's code\. - -To output logs from your function code, you can use methods on [the fmt package](https://golang.org/pkg/fmt/), or any logging library that writes to `stdout` or `stderr`\. The following example uses [the log package](https://golang.org/pkg/log/)\. - -**Example [main\.go](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/blank-go/function/main.go) – Logging** - -``` -func handleRequest(ctx context.Context, event events.SQSEvent) (string, error) { - // event - eventJson, _ := json.MarshalIndent(event, "", " ") - log.Printf("EVENT: %s", eventJson) - // environment variables - log.Printf("REGION: %s", os.Getenv("AWS_REGION")) - log.Println("ALL ENV VARS:") - for _, element := range os.Environ() { - log.Println(element) - } -``` - -**Example Log format** - -``` -START RequestId: dbda340c-xmpl-4031-8810-11bb609b4c71 Version: $LATEST -2020/03/27 03:40:05 EVENT: { - "Records": [ - { - "messageId": "19dd0b57-b21e-4ac1-bd88-01bbb068cb78", - "receiptHandle": "MessageReceiptHandle", - "body": "Hello from SQS!", - "md5OfBody": "7b27xmplb47ff90a553787216d55d91d", - "md5OfMessageAttributes": "", - "attributes": { - "ApproximateFirstReceiveTimestamp": "1523232000001", - "ApproximateReceiveCount": "1", - "SenderId": "123456789012", - "SentTimestamp": "1523232000000" - }, - ... -2020/03/27 03:40:05 AWS_LAMBDA_LOG_STREAM_NAME=2020/03/27/[$LATEST]569cxmplc3c34c7489e6a97ad08b4419 -2020/03/27 03:40:05 AWS_LAMBDA_FUNCTION_NAME=blank-go-function-9DV3XMPL6XBC -2020/03/27 03:40:05 AWS_LAMBDA_FUNCTION_MEMORY_SIZE=128 -2020/03/27 03:40:05 AWS_LAMBDA_FUNCTION_VERSION=$LATEST -2020/03/27 03:40:05 AWS_EXECUTION_ENV=AWS_Lambda_go1.x -END RequestId: dbda340c-xmpl-4031-8810-11bb609b4c71 -REPORT RequestId: dbda340c-xmpl-4031-8810-11bb609b4c71 Duration: 38.66 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 54 MB Init Duration: 203.69 ms -XRAY TraceId: 1-5e7d7595-212fxmpl9ee07c4884191322 SegmentId: 42ffxmpl0645f474 Sampled: true -``` - -The Go runtime logs the `START`, `END`, and `REPORT` lines for each invocation\. The report line provides the following details\. - -**Report Log** -+ **RequestId** – The unique request ID for the invocation\. -+ **Duration** – The amount of time that your function's handler method spent processing the event\. -+ **Billed Duration** – The amount of time billed for the invocation\. -+ **Memory Size** – The amount of memory allocated to the function\. -+ **Max Memory Used** – The amount of memory used by the function\. -+ **Init Duration** – For the first request served, the amount of time it took the runtime to load the function and run code outside of the handler method\. -+ **XRAY TraceId** – For traced requests, the [AWS X\-Ray trace ID](lambda-x-ray.md)\. -+ **SegmentId** – For traced requests, the X\-Ray segment ID\. -+ **Sampled** – For traced requests, the sampling result\. - -You can view logs in the Lambda console, in the CloudWatch Logs console, or from the command line\. - -**Topics** -+ [Viewing logs in the AWS Management Console](#golang-logging-console) -+ [Using the AWS CLI](#golang-logging-cli) -+ [Deleting logs](#golang-logging-delete) - -## Viewing logs in the AWS Management Console - -The Lambda console shows log output when you test a function on the function configuration page\. To view logs for all invocations, use the CloudWatch Logs console\. - -**To view your Lambda function's logs** - -1. Open the [Logs page of the CloudWatch console](https://console.aws.amazon.com/cloudwatch/home?#logs:)\. - -1. Choose the log group for your function \(**/aws/lambda/*function\-name***\)\. - -1. Choose the first stream in the list\. - -Each log stream corresponds to an [instance of your function](runtimes-context.md)\. New streams appear when you update your function and when additional instances are created to handle multiple concurrent invocations\. To find logs for specific invocations, you can instrument your function with X\-Ray, and record details about the request and log stream in the trace\. For a sample application that correlates logs and traces with X\-Ray, see [Error processor sample application for AWS Lambda](samples-errorprocessor.md)\. - -## Using the AWS CLI - -To get logs for an invocation from the command line, use the `--log-type` option\. The response includes a `LogResult` field that contains up to 4 KB of base64\-encoded logs from the invocation\. - -``` -$ aws lambda invoke --function-name my-function out --log-type Tail -{ - "StatusCode": 200, - "LogResult": "U1RBUlQgUmVxdWVzdElkOiA4N2QwNDRiOC1mMTU0LTExZTgtOGNkYS0yOTc0YzVlNGZiMjEgVmVyc2lvb...", - "ExecutedVersion": "$LATEST" -} -``` - -You can use the `base64` utility to decode the logs\. - -``` -$ aws lambda invoke --function-name my-function out --log-type Tail \ ---query 'LogResult' --output text | base64 -d -START RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 Version: $LATEST - "AWS_SESSION_TOKEN": "AgoJb3JpZ2luX2VjELj...", "_X_AMZN_TRACE_ID": "Root=1-5d02e5ca-f5792818b6fe8368e5b51d50;Parent=191db58857df8395;Sampled=0"",ask/lib:/opt/lib", -END RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 -REPORT RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 Duration: 79.67 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 73 MB -``` - -The `base64` utility is available on Linux, macOS, and [Ubuntu on Windows](https://docs.microsoft.com/en-us/windows/wsl/install-win10)\. For macOS, the command is `base64 -D`\. - -To get full log events from the command line, you can include the log stream name in the output of your function, as shown in the preceding example\. The following example script invokes a function named `my-function` and downloads the last five log events\. - -**Example get\-logs\.sh Script** -This example requires that `my-function` returns a log stream ID\. - -``` -#!/bin/bash -aws lambda invoke --function-name my-function --payload '{"key": "value"}' out -sed -i'' -e 's/"//g' out -sleep 15 -aws logs get-log-events --log-group-name /aws/lambda/my-function --log-stream-name $(cat out) --limit 5 -``` - -The script uses `sed` to remove quotes from the output file, and sleeps for 15 seconds to allow time for the logs to be available\. The output includes the response from Lambda and the output from the `get-log-events` command\. - -``` -$ ./get-logs.sh -{ - "StatusCode": 200, - "ExecutedVersion": "$LATEST" -} -{ - "events": [ - { - "timestamp": 1559763003171, - "message": "START RequestId: 4ce9340a-b765-490f-ad8a-02ab3415e2bf Version: $LATEST\n", - "ingestionTime": 1559763003309 - }, - { - "timestamp": 1559763003173, - "message": "2019-06-05T19:30:03.173Z\t4ce9340a-b765-490f-ad8a-02ab3415e2bf\tINFO\tENVIRONMENT VARIABLES\r{\r \"AWS_LAMBDA_FUNCTION_VERSION\": \"$LATEST\",\r ...", - "ingestionTime": 1559763018353 - }, - { - "timestamp": 1559763003173, - "message": "2019-06-05T19:30:03.173Z\t4ce9340a-b765-490f-ad8a-02ab3415e2bf\tINFO\tEVENT\r{\r \"key\": \"value\"\r}\n", - "ingestionTime": 1559763018353 - }, - { - "timestamp": 1559763003218, - "message": "END RequestId: 4ce9340a-b765-490f-ad8a-02ab3415e2bf\n", - "ingestionTime": 1559763018353 - }, - { - "timestamp": 1559763003218, - "message": "REPORT RequestId: 4ce9340a-b765-490f-ad8a-02ab3415e2bf\tDuration: 26.73 ms\tBilled Duration: 100 ms \tMemory Size: 128 MB\tMax Memory Used: 75 MB\t\n", - "ingestionTime": 1559763018353 - } - ], - "nextForwardToken": "f/34783877304859518393868359594929986069206639495374241795", - "nextBackwardToken": "b/34783877303811383369537420289090800615709599058929582080" -} -``` - -## Deleting logs - -Log groups aren't deleted automatically when you delete a function\. To avoid storing logs indefinitely, delete the log group, or [configure a retention period](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Working-with-log-groups-and-streams.html#SettingLogRetention) after which logs are deleted automatically\. \ No newline at end of file diff --git a/doc_source/golang-package.md b/doc_source/golang-package.md deleted file mode 100644 index 0631c428..00000000 --- a/doc_source/golang-package.md +++ /dev/null @@ -1,56 +0,0 @@ -# AWS Lambda deployment package in Go - -To create a Lambda function you first create a Lambda function deployment package, a \.zip file consisting of your code \(a Go executable\) and any dependencies\. - -After you create a deployment package, you may either upload it directly or upload the \.zip file first to an Amazon S3 bucket in the same AWS region where you want to create the Lambda function, and then specify the bucket name and object key name when you create the Lambda function using the console or the AWS CLI\. - -Download the Lambda library for Go with `go get`, and compile your executable\. - -``` -~/my-function$ go get github.com/aws/aws-lambda-go/lambda -~/my-function$ GOOS=linux go build main.go -``` - -Setting `GOOS` to `linux` ensures that the compiled executable is compatible with the [Go runtime](lambda-runtimes.md), even if you compile it in a non\-Linux environment\. - -Create a deployment package by packaging the executable in a ZIP file, and use the AWS CLI to create a function\. The handler parameter must match the name of the executable containing your handler\. - -``` -~/my-function$ zip function.zip main -~/my-function$ aws lambda create-function --function-name my-function --runtime go1.x \ - --zip-file fileb://function.zip --handler main \ - --role arn:aws:iam::123456789012:role/execution_role -``` - -## Creating a deployment package on Windows - -To create a \.zip that will work on AWS Lambda using Windows, we recommend installing the **build\-lambda\-zip** tool\. - -**Note** -If you have not already done so, you will need to install [git](https://git-scm.com/) and then add the `git` executable to your Windows `%PATH%` environment variable\. - -To download the tool, run the following command: - -``` -go.exe get -u github.com/aws/aws-lambda-go/cmd/build-lambda-zip -``` - -Use the tool from your `GOPATH`\. If you have a default installation of Go, the tool will typically be in `%USERPROFILE%\Go\bin`\. Otherwise, navigate to where you installed the Go runtime and do the following: - -In cmd\.exe, run the following: - -``` -set GOOS=linux -go build -o main main.go -%USERPROFILE%\Go\bin\build-lambda-zip.exe -output main.zip main -``` - -In Powershell, run the following: - -``` -$env:GOOS = "linux" -$env:CGO_ENABLED = "0" -$env:GOARCH = "amd64" -go build -o main main.go -~\Go\Bin\build-lambda-zip.exe -output main.zip main -``` \ No newline at end of file diff --git a/doc_source/golang-tracing.md b/doc_source/golang-tracing.md deleted file mode 100644 index f260a124..00000000 --- a/doc_source/golang-tracing.md +++ /dev/null @@ -1,84 +0,0 @@ -# Instrumenting Go code in AWS Lambda - -You can use the [X\-Ray SDK for Go](https://github.com/aws/aws-xray-sdk-go) with your Lambda function\. If your handler includes [AWS Lambda context object in Go](golang-context.md) as its first argument, that object can be passed to the X\-Ray SDK\. Lambda passes values through this context that the SDK can use to attach subsegments to the Lambda invoke service segment\. Subsegments created with the SDK will appear as a part of your Lambda traces\. - -## Installing the X\-Ray SDK - -Use the following command to install the X\-Ray SDK for Go\. \(The SDK's non\-testing dependencies will be included\)\. - -``` -go get -u github.com/aws/aws-xray-sdk-go/... -``` - -If you want to include the test dependencies, use the following command: - -``` -go get -u -t github.com/aws/aws-xray-sdk-go/... -``` - -You can also use [Glide](https://github.com/Masterminds/glide/blob/master/README.md) to manage dependencies\. - -``` -glide install -``` - -## Configuring the X\-Ray - -The following code sample illustrates how to configure the X\-Ray SDK for Go in your Lambda function: - -``` -import ( - "github.com/aws/aws-xray-sdk-go/xray" -) -func myHandlerFunction(ctx context.Context, sample string) { - xray.Configure(xray.Config{ - LogLevel: "info", // default - ServiceVersion: "1.2.3", - }) - ... //remaining handler code -} -``` - -## Creating a subsegment - -The following code illustrates how to start a subsegment: - -``` -// Start a subsegment - ctx, subSeg := xray.BeginSubsegment(ctx, "subsegment-name") - // ... - // Add metadata or annotation here if necessary - // ... - subSeg.Close(nil) -``` - -The following code illustrates how to trace and capture a critical code path: - -``` -func criticalSection(ctx context.Context) { - // This example traces a critical code path using a custom subsegment - xray.Capture(ctx, "MyService.criticalSection", func(ctx1 context.Context) error { - var err error - - section.Lock() - result := someLockedResource.Go() - section.Unlock() - - xray.AddMetadata(ctx1, "ResourceResult", result) - }) -} -``` - -## Tracing HTTP requests - -You can also use the `xray.Client()` method if you want to trace an HTTP client, as shown below: - -``` -func myFunction (ctx context.Context) ([]byte, error) { - resp, err := ctxhttp.Get(ctx, xray.Client(nil), "https://aws.amazon.com") - if err != nil { - return nil, err - } - return ioutil.ReadAll(resp.Body), nil -} -``` \ No newline at end of file diff --git a/doc_source/index.md b/doc_source/index.md deleted file mode 100644 index d0378139..00000000 --- a/doc_source/index.md +++ /dev/null @@ -1,276 +0,0 @@ -# AWS Lambda Developer Guide - ------ -*****Copyright © 2020 Amazon Web Services, Inc. and/or its affiliates. All rights reserved.***** - ------ -Amazon's trademarks and trade dress may not be used in - connection with any product or service that is not Amazon's, - in any manner that is likely to cause confusion among customers, - or in any manner that disparages or discredits Amazon. All other - trademarks not owned by Amazon are the property of their respective - owners, who may or may not be affiliated with, connected to, or - sponsored by Amazon. - ------ -## Contents -+ [What is AWS Lambda?](welcome.md) -+ [Getting started with AWS Lambda](getting-started.md) - + [Create a Lambda function with the console](getting-started-create-function.md) - + [Creating functions using the AWS Lambda console editor](code-editor.md) - + [Using AWS Lambda with the AWS Command Line Interface](gettingstarted-awscli.md) - + [AWS Lambda concepts](gettingstarted-concepts.md) - + [AWS Lambda features](gettingstarted-features.md) - + [Tools for working with AWS Lambda](gettingstarted-tools.md) - + [AWS Lambda limits](gettingstarted-limits.md) -+ [AWS Lambda permissions](lambda-permissions.md) - + [AWS Lambda execution role](lambda-intro-execution-role.md) - + [Using resource-based policies for AWS Lambda](access-control-resource-based.md) - + [Identity-based IAM policies for AWS Lambda](access-control-identity-based.md) - + [Resources and conditions for Lambda actions](lambda-api-permissions-ref.md) - + [Using permissions boundaries for AWS Lambda applications](permissions-boundary.md) -+ [Managing AWS Lambda functions](lambda-functions.md) - + [Configuring functions in the AWS Lambda console](configuration-console.md) - + [Using AWS Lambda environment variables](configuration-envvars.md) - + [Managing concurrency for a Lambda function](configuration-concurrency.md) - + [AWS Lambda function versions](configuration-versions.md) - + [AWS Lambda function aliases](configuration-aliases.md) - + [AWS Lambda layers](configuration-layers.md) - + [Configuring a Lambda function to access resources in a VPC](configuration-vpc.md) - + [Configuring database access for a Lambda function](configuration-database.md) - + [Tagging Lambda Functions](configuration-tags.md) -+ [Invoking AWS Lambda functions](lambda-invocation.md) - + [Synchronous invocation](invocation-sync.md) - + [Asynchronous invocation](invocation-async.md) - + [AWS Lambda event source mappings](invocation-eventsourcemapping.md) - + [Monitoring the state of a function with the Lambda API](functions-states.md) - + [AWS Lambda function scaling](invocation-scaling.md) - + [Error handling and automatic retries in AWS Lambda](invocation-retries.md) - + [Invoking Lambda functions with the AWS Mobile SDK for Android](with-on-demand-custom-android.md) - + [Tutorial: Using AWS Lambda with the Mobile SDK for Android](with-android-example.md) - + [Sample function code](with-android-create-package.md) -+ [AWS Lambda runtimes](lambda-runtimes.md) - + [AWS Lambda execution context](runtimes-context.md) - + [Runtime support policy](runtime-support-policy.md) - + [Custom AWS Lambda runtimes](runtimes-custom.md) - + [AWS Lambda runtime interface](runtimes-api.md) - + [Tutorial – Publishing a custom runtime](runtimes-walkthrough.md) -+ [AWS Lambda applications](deploying-lambda-apps.md) - + [Managing applications in the AWS Lambda console](applications-console.md) - + [Creating an application with continuous delivery in the Lambda console](applications-tutorial.md) - + [Rolling deployments for Lambda functions](lambda-rolling-deployments.md) - + [Common Lambda application types and use cases](applications-usecases.md) - + [Best Practices for Working with AWS Lambda Functions](best-practices.md) -+ [Using AWS Lambda with other services](lambda-services.md) - + [Using AWS Lambda with an Application Load Balancer](services-alb.md) - + [Using AWS Lambda with Alexa](services-alexa.md) - + [Using AWS Lambda with Amazon API Gateway](services-apigateway.md) - + [Tutorial: Using AWS Lambda with Amazon API Gateway](services-apigateway-tutorial.md) - + [Sample function code](services-apigateway-code.md) - + [Create a simple microservice using Lambda and API Gateway](services-apigateway-blueprint.md) - + [AWS SAM template for an API Gateway application](services-apigateway-template.md) - + [Using AWS Lambda with AWS CloudTrail](with-cloudtrail.md) - + [Tutorial: Triggering a Lambda function with AWS CloudTrail events](with-cloudtrail-example.md) - + [Sample function code](with-cloudtrail-create-package.md) - + [Using AWS Lambda with Amazon CloudWatch Events](services-cloudwatchevents.md) - + [Tutorial: Using AWS Lambda with scheduled events](services-cloudwatchevents-tutorial.md) - + [AWS SAM template for a CloudWatch Events application](with-scheduledevents-example-use-app-spec.md) - + [Schedule expressions using rate or cron](services-cloudwatchevents-expressions.md) - + [Using AWS Lambda with Amazon CloudWatch Logs](services-cloudwatchlogs.md) - + [Using AWS Lambda with AWS CloudFormation](services-cloudformation.md) - + [Using AWS Lambda with CloudFront Lambda@Edge](lambda-edge.md) - + [Using AWS Lambda with AWS CodeCommit](services-codecommit.md) - + [Using AWS Lambda with AWS CodePipeline](services-codepipeline.md) - + [Building a continuous delivery pipeline for a Lambda application with AWS CodePipeline](build-pipeline.md) - + [Using AWS Lambda with Amazon Cognito](services-cognito.md) - + [Using AWS Lambda with AWS Config](services-config.md) - + [Using AWS Lambda with Amazon DynamoDB](with-ddb.md) - + [Tutorial: Using AWS Lambda with Amazon DynamoDB streams](with-ddb-example.md) - + [Sample function code](with-ddb-create-package.md) - + [AWS SAM template for a DynamoDB application](kinesis-tutorial-spec.md) - + [Tutorial: Configuring a Lambda function to access Amazon ElastiCache in an Amazon VPC](services-elasticache-tutorial.md) - + [Using AWS Lambda with Amazon EC2](services-ec2.md) - + [Tutorial: Using AWS SDK for .NET to manage Amazon EC2 Spot Instances](services-ec2-tutorial.md) - + [Using AWS Lambda with AWS IoT](services-iot.md) - + [Using AWS Lambda with AWS IoT Events](services-iotevents.md) - + [Using AWS Lambda with Amazon Kinesis](with-kinesis.md) - + [Tutorial: Using AWS Lambda with Amazon Kinesis](with-kinesis-example.md) - + [Sample function code](with-kinesis-create-package.md) - + [AWS SAM template for a Kinesis application](with-kinesis-example-use-app-spec.md) - + [Using AWS Lambda with Amazon Kinesis Data Firehose](services-kinesisfirehose.md) - + [Using AWS Lambda with Amazon Lex](services-lex.md) - + [Using AWS Lambda with Amazon RDS](services-rds.md) - + [Tutorial: Configuring a Lambda function to access Amazon RDS in an Amazon VPC](services-rds-tutorial.md) - + [Using AWS Lambda with Amazon S3 events](with-s3.md) - + [Tutorial: Using AWS Lambda with Amazon S3](with-s3-example.md) - + [Sample Amazon S3 function code](with-s3-example-deployment-pkg.md) - + [AWS SAM template for an Amazon S3 application](with-s3-example-use-app-spec.md) - + [Using AWS Lambda with Amazon S3 batch operations](services-s3-batch.md) - + [Using AWS Lambda with Amazon SES](services-ses.md) - + [Using AWS Lambda with Amazon SNS](with-sns.md) - + [Tutorial: Using AWS Lambda with Amazon Simple Notification Service](with-sns-example.md) - + [Sample function code](with-sns-create-package.md) - + [Using AWS Lambda with Amazon SQS](with-sqs.md) - + [Tutorial: Using AWS Lambda with Amazon Simple Queue Service](with-sqs-example.md) - + [Sample Amazon SQS function code](with-sqs-create-package.md) - + [AWS SAM template for an Amazon SQS application](with-sqs-example-use-app-spec.md) -+ [Lambda sample applications](lambda-samples.md) - + [Blank function sample application for AWS Lambda](samples-blank.md) - + [Error processor sample application for AWS Lambda](samples-errorprocessor.md) -+ [Building Lambda functions with Node.js](lambda-nodejs.md) - + [AWS Lambda function handler in Node.js](nodejs-handler.md) - + [AWS Lambda deployment package in Node.js](nodejs-package.md) - + [AWS Lambda context object in Node.js](nodejs-context.md) - + [AWS Lambda function logging in Node.js](nodejs-logging.md) - + [AWS Lambda function errors in Node.js](nodejs-exceptions.md) - + [Instrumenting Node.js code in AWS Lambda](nodejs-tracing.md) -+ [Building Lambda functions with Python](lambda-python.md) - + [AWS Lambda function handler in Python](python-handler.md) - + [AWS Lambda deployment package in Python](python-package.md) - + [AWS Lambda context object in Python](python-context.md) - + [AWS Lambda function logging in Python](python-logging.md) - + [AWS Lambda function errors in Python](python-exceptions.md) - + [Instrumenting Python code in AWS Lambda](python-tracing.md) -+ [Building Lambda functions with Ruby](lambda-ruby.md) - + [AWS Lambda function handler in Ruby](ruby-handler.md) - + [AWS Lambda deployment package in Ruby](ruby-package.md) - + [AWS Lambda context object in Ruby](ruby-context.md) - + [AWS Lambda function logging in Ruby](ruby-logging.md) - + [AWS Lambda function errors in Ruby](ruby-exceptions.md) -+ [Building Lambda functions with Java](lambda-java.md) - + [Java sample applications for AWS Lambda](java-samples.md) - + [AWS Lambda deployment package in Java](java-package.md) - + [AWS Lambda function handler in Java](java-handler.md) - + [AWS Lambda context object in Java](java-context.md) - + [AWS Lambda function logging in Java](java-logging.md) - + [AWS Lambda function errors in Java](java-exceptions.md) - + [Instrumenting Java code in AWS Lambda](java-tracing.md) - + [Creating a deployment package using Eclipse](java-package-eclipse.md) -+ [Building Lambda functions with Go](lambda-golang.md) - + [AWS Lambda deployment package in Go](golang-package.md) - + [AWS Lambda function handler in Go](golang-handler.md) - + [AWS Lambda context object in Go](golang-context.md) - + [AWS Lambda function logging in Go](golang-logging.md) - + [AWS Lambda function errors in Go](golang-exceptions.md) - + [Instrumenting Go code in AWS Lambda](golang-tracing.md) - + [Using environment variables](golang-envvars.md) -+ [Building Lambda functions with C#](lambda-csharp.md) - + [AWS Lambda Deployment Package in C#](csharp-package.md) - + [.NET Core CLI](csharp-package-cli.md) - + [AWS Toolkit for Visual Studio](csharp-package-toolkit.md) - + [AWS Lambda function handler in C#](csharp-handler.md) - + [AWS Lambda context object in C#](csharp-context.md) - + [AWS Lambda function logging in C#](csharp-logging.md) - + [AWS Lambda function errors in C#](csharp-exceptions.md) -+ [Building Lambda functions with PowerShell](lambda-powershell.md) - + [Setting Up a PowerShell Development Environment](powershell-devenv.md) - + [AWS Lambda deployment package in PowerShell](powershell-package.md) - + [AWS Lambda function handler in PowerShell](powershell-handler.md) - + [AWS Lambda context object in PowerShell](powershell-context.md) - + [AWS Lambda function logging in PowerShell](powershell-logging.md) - + [AWS Lambda function errors in PowerShell](powershell-exceptions.md) -+ [Monitoring and troubleshooting Lambda applications](lambda-monitoring.md) - + [Monitoring functions in the AWS Lambda console](monitoring-functions-access-metrics.md) - + [Working with AWS Lambda function metrics](monitoring-metrics.md) - + [Accessing Amazon CloudWatch logs for AWS Lambda](monitoring-cloudwatchlogs.md) - + [Using AWS X-Ray](lambda-x-ray.md) - + [Tracing Lambda-based applications with AWS X-Ray](using-x-ray.md) - + [Emitting trace segments from a Lambda function](downstream-tracing.md) - + [The AWS X-Ray daemon in the Lambda environment](lambda-x-ray-daemon.md) - + [Logging AWS Lambda API calls with AWS CloudTrail](logging-using-cloudtrail.md) -+ [Security in AWS Lambda](lambda-security.md) - + [Data protection in AWS Lambda](security-dataprotection.md) - + [Identity and access management for AWS Lambda](security-iam.md) - + [How AWS Lambda works with IAM](security_iam_service-with-iam.md) - + [AWS Lambda identity-based policy examples](security_iam_id-based-policy-examples.md) - + [Troubleshooting AWS Lambda identity and access](security_iam_troubleshoot.md) - + [Compliance validation for AWS Lambda](security-compliance.md) - + [Resilience in AWS Lambda](security-resilience.md) - + [Infrastructure security in AWS Lambda](security-infrastructure.md) - + [Configuration and vulnerability analysis in AWS Lambda](security-configuration.md) -+ [Troubleshooting issues in AWS Lambda](lambda-troubleshooting.md) - + [Troubleshoot deployment issues in AWS Lambda](troubleshooting-deployment.md) - + [Troubleshoot invocation issues in AWS Lambda](troubleshooting-invocation.md) - + [Troubleshoot execution issues in AWS Lambda](troubleshooting-execution.md) - + [Troubleshoot networking issues in AWS Lambda](troubleshooting-networking.md) -+ [AWS Lambda releases](lambda-releases.md) -+ [API reference](API_Reference.md) - + [Actions](API_Operations.md) - + [AddLayerVersionPermission](API_AddLayerVersionPermission.md) - + [AddPermission](API_AddPermission.md) - + [CreateAlias](API_CreateAlias.md) - + [CreateEventSourceMapping](API_CreateEventSourceMapping.md) - + [CreateFunction](API_CreateFunction.md) - + [DeleteAlias](API_DeleteAlias.md) - + [DeleteEventSourceMapping](API_DeleteEventSourceMapping.md) - + [DeleteFunction](API_DeleteFunction.md) - + [DeleteFunctionConcurrency](API_DeleteFunctionConcurrency.md) - + [DeleteFunctionEventInvokeConfig](API_DeleteFunctionEventInvokeConfig.md) - + [DeleteLayerVersion](API_DeleteLayerVersion.md) - + [DeleteProvisionedConcurrencyConfig](API_DeleteProvisionedConcurrencyConfig.md) - + [GetAccountSettings](API_GetAccountSettings.md) - + [GetAlias](API_GetAlias.md) - + [GetEventSourceMapping](API_GetEventSourceMapping.md) - + [GetFunction](API_GetFunction.md) - + [GetFunctionConcurrency](API_GetFunctionConcurrency.md) - + [GetFunctionConfiguration](API_GetFunctionConfiguration.md) - + [GetFunctionEventInvokeConfig](API_GetFunctionEventInvokeConfig.md) - + [GetLayerVersion](API_GetLayerVersion.md) - + [GetLayerVersionByArn](API_GetLayerVersionByArn.md) - + [GetLayerVersionPolicy](API_GetLayerVersionPolicy.md) - + [GetPolicy](API_GetPolicy.md) - + [GetProvisionedConcurrencyConfig](API_GetProvisionedConcurrencyConfig.md) - + [Invoke](API_Invoke.md) - + [InvokeAsync](API_InvokeAsync.md) - + [ListAliases](API_ListAliases.md) - + [ListEventSourceMappings](API_ListEventSourceMappings.md) - + [ListFunctionEventInvokeConfigs](API_ListFunctionEventInvokeConfigs.md) - + [ListFunctions](API_ListFunctions.md) - + [ListLayers](API_ListLayers.md) - + [ListLayerVersions](API_ListLayerVersions.md) - + [ListProvisionedConcurrencyConfigs](API_ListProvisionedConcurrencyConfigs.md) - + [ListTags](API_ListTags.md) - + [ListVersionsByFunction](API_ListVersionsByFunction.md) - + [PublishLayerVersion](API_PublishLayerVersion.md) - + [PublishVersion](API_PublishVersion.md) - + [PutFunctionConcurrency](API_PutFunctionConcurrency.md) - + [PutFunctionEventInvokeConfig](API_PutFunctionEventInvokeConfig.md) - + [PutProvisionedConcurrencyConfig](API_PutProvisionedConcurrencyConfig.md) - + [RemoveLayerVersionPermission](API_RemoveLayerVersionPermission.md) - + [RemovePermission](API_RemovePermission.md) - + [TagResource](API_TagResource.md) - + [UntagResource](API_UntagResource.md) - + [UpdateAlias](API_UpdateAlias.md) - + [UpdateEventSourceMapping](API_UpdateEventSourceMapping.md) - + [UpdateFunctionCode](API_UpdateFunctionCode.md) - + [UpdateFunctionConfiguration](API_UpdateFunctionConfiguration.md) - + [UpdateFunctionEventInvokeConfig](API_UpdateFunctionEventInvokeConfig.md) - + [Data Types](API_Types.md) - + [AccountLimit](API_AccountLimit.md) - + [AccountUsage](API_AccountUsage.md) - + [AliasConfiguration](API_AliasConfiguration.md) - + [AliasRoutingConfiguration](API_AliasRoutingConfiguration.md) - + [Concurrency](API_Concurrency.md) - + [DeadLetterConfig](API_DeadLetterConfig.md) - + [DestinationConfig](API_DestinationConfig.md) - + [Environment](API_Environment.md) - + [EnvironmentError](API_EnvironmentError.md) - + [EnvironmentResponse](API_EnvironmentResponse.md) - + [EventSourceMappingConfiguration](API_EventSourceMappingConfiguration.md) - + [FunctionCode](API_FunctionCode.md) - + [FunctionCodeLocation](API_FunctionCodeLocation.md) - + [FunctionConfiguration](API_FunctionConfiguration.md) - + [FunctionEventInvokeConfig](API_FunctionEventInvokeConfig.md) - + [Layer](API_Layer.md) - + [LayersListItem](API_LayersListItem.md) - + [LayerVersionContentInput](API_LayerVersionContentInput.md) - + [LayerVersionContentOutput](API_LayerVersionContentOutput.md) - + [LayerVersionsListItem](API_LayerVersionsListItem.md) - + [OnFailure](API_OnFailure.md) - + [OnSuccess](API_OnSuccess.md) - + [ProvisionedConcurrencyConfigListItem](API_ProvisionedConcurrencyConfigListItem.md) - + [TracingConfig](API_TracingConfig.md) - + [TracingConfigResponse](API_TracingConfigResponse.md) - + [VpcConfig](API_VpcConfig.md) - + [VpcConfigResponse](API_VpcConfigResponse.md) -+ [AWS glossary](glossary.md) \ No newline at end of file diff --git a/doc_source/invocation-async.md b/doc_source/invocation-async.md deleted file mode 100644 index 868b4f4e..00000000 --- a/doc_source/invocation-async.md +++ /dev/null @@ -1,235 +0,0 @@ -# Asynchronous invocation - -Several AWS services, such as Amazon Simple Storage Service \(Amazon S3\) and Amazon Simple Notification Service \(Amazon SNS\), invoke functions asynchronously to process events\. When you invoke a function asynchronously, you don't wait for a response from the function code\. You hand off the event to Lambda and Lambda handles the rest\. You can configure how Lambda handles errors, and can send invocation records to a downstream resource to chain together components of your application\. - -The following diagram shows clients invoking a Lambda function asynchronously\. Lambda queues the events before sending them to the function\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-async.png) - -For asynchronous invocation, Lambda places the event in a queue and returns a success response without additional information\. A separate process reads events from the queue and sends them to your function\. To invoke a function asynchronously, set the invocation type parameter to `Event`\. - -``` -$ aws lambda invoke --function-name my-function --invocation-type Event --payload '{ "key": "value" }' response.json -{ - "StatusCode": 202 -} -``` - -The output file \(`response.json`\) doesn't contain any information, but is still created when you run this command\. If Lambda isn't able to add the event to the queue, the error message appears in the command output\. - -Lambda manages the function's asynchronous event queue and attempts to retry on errors\. If the function returns an error, Lambda attempts to run it two more times, with a one\-minute wait between the first two attempts, and two minutes between the second and third attempts\. Function errors include errors returned by the function's code and errors returned by the function's runtime, such as timeouts\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/invocation-types-retries.png) - -If the function doesn't have enough concurrency available to process all events, additional requests are throttled\. For throttling errors \(429\) and system errors \(500\-series\), Lambda returns the event to the queue and attempts to run the function again for up to 6 hours\. The retry interval increases exponentially from 1 second after the first attempt to a maximum of 5 minutes\. However, it might be longer if the queue is backed up\. Lambda also reduces the rate at which it reads events from the queue\. - -The following example shows an event that was successfully added to the queue, but is still pending one hour later due to throttling\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/invocation-types-throttle.png) - -Even if your function doesn't return an error, it's possible for it to receive the same event from Lambda multiple times because the queue itself is eventually consistent\. If the function can't keep up with incoming events, events might also be deleted from the queue without being sent to the function\. Ensure that your function code gracefully handles duplicate events, and that you have enough concurrency available to handle all invocations\. - -When the queue is backed up, new events might age out before Lambda has a chance to send them to your function\. When an event expires or fails all processing attempts, Lambda discards it\. You can [configure error handling](#invocation-async-errors) for a function to reduce the number of retries that Lambda performs, or to discard unprocessed events more quickly\. - -You can also configure Lambda to send an invocation record to another service\. Lambda supports the following [destinations](#invocation-async-destinations) for asynchronous invocation\. -+ **Amazon SQS** – A standard SQS queue\. -+ **Amazon SNS** – An SNS topic\. -+ **AWS Lambda** – A Lambda function\. -+ **Amazon EventBridge** – An EventBridge event bus\. - -The invocation record contains details about the request and response in JSON format\. You can configure separate destinations for events that are processed successfully, and events that fail all processing attempts\. Alternatively, you can configure an SQS queue or SNS topic as a [dead\-letter queue](#dlq) for discarded events\. For dead\-letter queues, Lambda only sends the content of the event, without details about the response\. - -**Topics** -+ [Configuring error handling for asynchronous invocation](#invocation-async-errors) -+ [Configuring destinations for asynchronous invocation](#invocation-async-destinations) -+ [Asynchronous invocation configuration API](#invocation-async-api) -+ [AWS Lambda function dead\-letter queues](#dlq) - -## Configuring error handling for asynchronous invocation - -Use the Lambda console to configure error handling settings on a function, a version, or an alias\. - -**To configure error handling** - -1. Open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions)\. - -1. Choose a function\. - -1. Under **Asynchronous invocation**, choose **Edit**\. - -1. Configure the following settings\. - + **Maximum age of event** – The maximum amount of time Lambda retains an event in the asynchronous event queue, up to 6 hours\. - + **Retry attempts** – The number of times Lambda retries when the function returns an error, between 0 and 2\. - -1. Choose **Save**\. - -When an invocation event exceeds the maximum age or fails all retry attempts, Lambda discards it\. To retain a copy of discarded events, configure a failed\-event destination\. - -## Configuring destinations for asynchronous invocation - -To send records of asynchronous invocations to another service, add a destination to your function\. You can configure separate destinations for events that fail processing and events that are successfully processed\. Like error handling settings, you can configure destinations on a function, a version, or an alias\. - -The following example shows a function that is processing asynchronous invocations\. When the function returns a success response or exits without throwing an error, Lambda sends a record of the invocation to an EventBridge event bus\. When an event fails all processing attempts, Lambda sends an invocation record to an Amazon SQS queue\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-destinations.png) - -To send events to a destination, your function needs additional permissions\. Add a policy with the required permissions to your function's [execution role](lambda-intro-execution-role.md)\. Each destination service requires a different permission, as follows: -+ **Amazon SQS** – [sqs:SendMessage](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SendMessage.html) -+ **Amazon SNS** – [sns:Publish](https://docs.aws.amazon.com/sns/latest/api/API_Publish.html) -+ **Lambda** – [lambda:InvokeFunction](https://docs.aws.amazon.com/lambda/latest/dg/API_Invoke.html) -+ **EventBridge** – [events:PutEvents](https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_PutEvents.html) - -Add destinations to your function in the Lambda console's function designer\. - -**To configure a destination for asynchronous invocation records** - -1. Open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions)\. - -1. Choose a function\. - -1. Under **Designer**, choose **Add destination**\. - -1. For **Source**, choose **Asynchronous invocation**\. - -1. For **Condition**, choose from the following options: - + **On failure** – Send a record when the event fails all processing attempts or exceeds the maximum age\. - + **On success** – Send a record when the function successfully processes an asynchronous invocation\. - -1. For **Destination type**, choose the type of resource that receives the invocation record\. - -1. For **Destination**, choose a resource\. - -1. Choose **Save**\. - -When an invocation matches the condition, Lambda sends a JSON document with details about the invocation to the destination\. The following example shows an invocation record for an event that failed three processing attempts due to a function error\. - -**Example Invocation record** - -``` -{ - "version": "1.0", - "timestamp": "2019-11-14T18:16:05.568Z", - "requestContext": { - "requestId": "e4b46cbf-b738-xmpl-8880-a18cdf61200e", - "functionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function:$LATEST", - "condition": "RetriesExhausted", - "approximateInvokeCount": 3 - }, - "requestPayload": { - "ORDER_IDS": [ - "9e07af03-ce31-4ff3-xmpl-36dce652cb4f", - "637de236-e7b2-464e-xmpl-baf57f86bb53", - "a81ddca6-2c35-45c7-xmpl-c3a03a31ed15" - ] - }, - "responseContext": { - "statusCode": 200, - "executedVersion": "$LATEST", - "functionError": "Unhandled" - }, - "responsePayload": { - "errorMessage": "RequestId: e4b46cbf-b738-xmpl-8880-a18cdf61200e Process exited before completing request" - } -} -``` - -The invocation record contains details about the event, the response, and the reason that the record was sent\. - -## Asynchronous invocation configuration API - -To manage asynchronous invocation settings with the AWS CLI or AWS SDK, use the following API operations\. -+ [PutFunctionEventInvokeConfig](https://docs.aws.amazon.com/lambda/latest/dg/API_PutFunctionEventInvokeConfig.html) -+ [GetFunctionEventInvokeConfig](https://docs.aws.amazon.com/lambda/latest/dg/API_GetFunctionEventInvokeConfig.html) -+ [UpdateFunctionEventInvokeConfig](https://docs.aws.amazon.com/lambda/latest/dg/API_UpdateFunctionEventInvokeConfig.html) -+ [ListFunctionEventInvokeConfigs](https://docs.aws.amazon.com/lambda/latest/dg/API_ListFunctionEventInvokeConfigs.html) -+ [DeleteFunctionEventInvokeConfig](https://docs.aws.amazon.com/lambda/latest/dg/API_DeleteFunctionEventInvokeConfig.html) - -To configure asynchronous invocation with the AWS CLI, use the `put-function-event-invoke-config` command\. The following example configures a function with a maximum event age of 1 hour and no retries\. - -``` -$ aws lambda put-function-event-invoke-config --function-name error \ ---maximum-event-age-in-seconds 3600 --maximum-retry-attempts 0 -{ - "LastModified": 1573686021.479, - "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:error:$LATEST", - "MaximumRetryAttempts": 0, - "MaximumEventAgeInSeconds": 3600, - "DestinationConfig": { - "OnSuccess": {}, - "OnFailure": {} - } -} -``` - -The `put-function-event-invoke-config` command overwrites any existing configuration on the function, version, or alias\. To configure an option without resetting others, use `update-function-event-invoke-config`\. The following example configures Lambda to send a record to an SQS queue named `destination` when an event can't be processed\. - -``` -$ aws lambda update-function-event-invoke-config --function-name error \ ---destination-config '{"OnFailure":{"Destination": "arn:aws:sqs:us-east-2:123456789012:destination"}}' -{ - "LastModified": 1573687896.493, - "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:error:$LATEST", - "MaximumRetryAttempts": 0, - "MaximumEventAgeInSeconds": 3600, - "DestinationConfig": { - "OnSuccess": {}, - "OnFailure": { - "Destination": "arn:aws:sqs:us-east-2:123456789012:destination" - } - } -} -``` - -## AWS Lambda function dead\-letter queues - -As an alternative to an [on\-failure destination](#invocation-async-destinations), you can configure your function with a dead\-letter queue to save discarded events for further processing\. A dead\-letter queue acts the same as an on\-failure destination in that it is used when an event fails all processing attempts or expires without being processed\. However, a dead\-letter queue is part of a function's version\-specific configuration, so it is locked in when you publish a version\. On\-failure destinations also support additional targets and include details about the function's response in the invocation record\. - -If you don't have a queue or topic, create one\. Choose the target type that matches your use case\. -+ [Amazon SQS queue](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-create-queue.html) – A queue holds failed events until they're retrieved\. You can retrieve events manually, or you can [configure Lambda to read from the queue](with-sqs.md) and invoke a function\. - - Create a queue in the [Amazon SQS console](https://console.aws.amazon.com/sqs)\. -+ [Amazon SNS topic](https://docs.aws.amazon.com/sns/latest/gsg/CreateTopic.html) – A topic relays failed events to one or more destinations\. You can configure a topic to send events to an email address, a Lambda function, or an HTTP endpoint\. - - Create a topic in the [Amazon SNS console](https://console.aws.amazon.com/sns/home)\. - -To send events to a queue or topic, your function needs additional permissions\. Add a policy with the required permissions to your function's [execution role](lambda-intro-execution-role.md)\. -+ **Amazon SQS** – [sqs:SendMessage](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SendMessage.html) -+ **Amazon SNS** – [sns:Publish](https://docs.aws.amazon.com/sns/latest/api/API_Publish.html) - -If the target queue or topic is encrypted with a customer managed key, the execution role must also be a user in the key's [resource\-based policy](https://docs.aws.amazon.com/kms/latest/developerguide/key-policies.html)\. - -After creating the target and updating your function's execution role, add the dead\-letter queue to your function\. You can configure multiple functions to send events to the same target\. - -**To configure a dead\-letter queue** - -1. Open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions)\. - -1. Choose a function\. - -1. Under **Asynchronous invocation**, choose **Edit**\. - -1. Set **DLQ resource** to **Amazon SQS** or **Amazon SNS**\. - -1. Choose the target queue or topic\. - -1. Choose **Save**\. - -To configure a dead\-letter queue with the AWS CLI, use the `update-function-configuration` command\. - -``` -$ aws lambda update-function-configuration --function-name my-function \ ---dead-letter-config TargetArn=arn:aws:sns:us-east-2:123456789012:my-topic -``` - -Lambda sends the event to the dead\-letter queue as\-is, with additional information in attributes\. You can use this information to identify the error that the function returned, or to correlate the event with logs or an AWS X\-Ray trace\. - -**Dead\-letter queue message attributes** -+ **RequestID** \(String\) – The ID of the invocation request\. Request IDs appear in function logs\. You can also use the X\-Ray SDK to record the request ID on an attribute in the trace\. You can then search for traces by request ID in the X\-Ray console\. For an example, see the [error processor sample](samples-errorprocessor.md)\. -+ **ErrorCode** \(Number\) – The HTTP status code\. -+ **ErrorMessage** \(String\) – The first 1 KB of the error message\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/invocation-dlq-attributes.png) - -If Lambda can't send a message to the dead\-letter queue, it deletes the event and emits the [DeadLetterErrors](monitoring-metrics.md) metric\. This can happen because of lack of permissions, or if the total size of the message exceeds the limit for the target queue or topic\. For example, if an Amazon SNS notification with a body close to 256 KB triggers a function that results in an error, the additional event data added by Amazon SNS, combined with the attributes added by Lambda, can cause the message to exceed the maximum size allowed in the dead\-letter queue\. - -If you're using Amazon SQS as an event source, configure a dead\-letter queue on the Amazon SQS queue itself and not on the Lambda function\. For more information, see [Using AWS Lambda with Amazon SQS](with-sqs.md)\. \ No newline at end of file diff --git a/doc_source/invocation-eventsourcemapping.md b/doc_source/invocation-eventsourcemapping.md deleted file mode 100644 index 7438b402..00000000 --- a/doc_source/invocation-eventsourcemapping.md +++ /dev/null @@ -1,93 +0,0 @@ -# AWS Lambda event source mappings - -An event source mapping is an AWS Lambda resource that reads from an event source and invokes a Lambda function\. You can use event source mappings to process items from a stream or queue in services that don't invoke Lambda functions directly\. Lambda provides event source mappings for the following services\. - -**Services that Lambda reads events from** -+ [Amazon Kinesis](with-kinesis.md) -+ [Amazon DynamoDB](with-ddb.md) -+ [Amazon Simple Queue Service](with-sqs.md) - -An event source mapping uses permissions in the function's [execution role](lambda-intro-execution-role.md) to read and manage items in the event source\. Permissions, event structure, settings, and polling behavior vary by event source\. For more information, see the linked topic for the service that you use as an event source\. - -To manage event source mappings with the AWS CLI or AWS SDK, use the following API actions: -+ [CreateEventSourceMapping](API_CreateEventSourceMapping.md) -+ [ListEventSourceMappings](API_ListEventSourceMappings.md) -+ [GetEventSourceMapping](API_GetEventSourceMapping.md) -+ [UpdateEventSourceMapping](API_UpdateEventSourceMapping.md) -+ [DeleteEventSourceMapping](API_DeleteEventSourceMapping.md) - -The following example uses the AWS CLI to map a function named `my-function` to a DynamoDB stream that is specified by its Amazon Resource Name \(ARN\), with a batch size of 500\. - -``` -$ aws lambda create-event-source-mapping --function-name my-function --batch-size 500 --starting-position LATEST \ ---event-source-arn arn:aws:dynamodb:us-east-2:123456789012:table/my-table/stream/2019-06-10T19:26:16.525 -{ - "UUID": "14e0db71-5d35-4eb5-b481-8945cf9d10c2", - "BatchSize": 500, - "MaximumBatchingWindowInSeconds": 0, - "ParallelizationFactor": 1, - "EventSourceArn": "arn:aws:dynamodb:us-east-2:123456789012:table/my-table/stream/2019-06-10T19:26:16.525", - "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function", - "LastModified": 1560209851.963, - "LastProcessingResult": "No records processed", - "State": "Creating", - "StateTransitionReason": "User action", - "DestinationConfig": {}, - "MaximumRecordAgeInSeconds": 604800, - "BisectBatchOnFunctionError": false, - "MaximumRetryAttempts": 10000 -} -``` - -Event source mappings read items from a stream or queue in batches\. They include multiple items in the event that your function receives\. You can configure the size of the batch that the event source mapping sends to your function, up to a maximum that varies by service\. The number of items in the event can be smaller than the batch size if there aren't enough items available, or if the batch is too large to send in one event and has to be split up\. - -The following example shows an event source mapping that reads from a Kinesis stream\. If a batch of events fails all processing attempts, the event source mapping sends details about the batch to an SQS queue\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-eventsourcemapping.png) - -The event batch is the event that Lambda sends to the function\. It is a batch of records or messages compiled from the items that the event source mapping reads from a stream or queue\. Batch size and other settings only apply to the event batch\. - -For streams, an event source mapping creates an iterator for each shard in the stream and processes items in each shard in order\. You can configure the event source mapping to read only new items that appear in the stream, or to start with older items\. Processed items aren't removed from the stream and can be processed by other functions or consumers\. - -By default, if your function returns an error, the entire batch is reprocessed until the function succeeds, or the items in the batch expire\. To ensure in\-order processing, processing for the affected shard is paused until the error is resolved\. You can configure the event source mapping to discard old events, restrict the number of retries, or process multiple batches in parallel\. If you process multiple batches in parallel, in\-order processing is still guaranteed for each partition key, but multiple partition keys in the same shard are processed simultaneously\. - -You can also configure the event source mapping to send an invocation record to another service when it discards an event batch\. Lambda supports the following [destinations](invocation-async.md#invocation-async-destinations) for event source mappings\. -+ **Amazon SQS** – An SQS queue\. -+ **Amazon SNS** – An SNS topic\. - -The invocation record contains details about the failed event batch in JSON format\. - -The following example shows an invocation record for a Kinesis stream\. - -**Example Invocation Record** - -``` -{ - "requestContext": { - "requestId": "c9b8fa9f-5a7f-xmpl-af9c-0c604cde93a5", - "functionArn": "arn:aws:lambda:us-east-2:123456789012:function:myfunction", - "condition": "RetryAttemptsExhausted", - "approximateInvokeCount": 1 - }, - "responseContext": { - "statusCode": 200, - "executedVersion": "$LATEST", - "functionError": "Unhandled" - }, - "version": "1.0", - "timestamp": "2019-11-14T00:38:06.021Z", - "KinesisBatchInfo": { - "shardId": "shardId-000000000001", - "startSequenceNumber": "49601189658422359378836298521827638475320189012309704722", - "endSequenceNumber": "49601189658422359378836298522902373528957594348623495186", - "approximateArrivalOfFirstRecord": "2019-11-14T00:38:04.835Z", - "approximateArrivalOfLastRecord": "2019-11-14T00:38:05.580Z", - "batchSize": 500, - "streamArn": "arn:aws:kinesis:us-east-2:123456789012:stream/mystream" - } -} -``` - -Lambda also supports in\-order processing for [FIFO \(first\-in, first\-out\) queues](with-sqs.md), scaling up to the number of active message groups\. For standard queues, items aren't necessarily processed in order\. Lambda scales up to process a standard queue as quickly as possible\. When an error occurs, batches are returned to the queue as individual items and might be processed in a different grouping than the original batch\. Occasionally, the event source mapping might receive the same item from the queue twice, even if no function error occurred\. Lambda deletes items from the queue after they're processed successfully\. You can configure the source queue to send items to a dead\-letter queue if they can't be processed\. - -For information about services that invoke Lambda functions directly, see [Using AWS Lambda with other services](lambda-services.md)\. \ No newline at end of file diff --git a/doc_source/invocation-retries.md b/doc_source/invocation-retries.md deleted file mode 100644 index 11efc02b..00000000 --- a/doc_source/invocation-retries.md +++ /dev/null @@ -1,43 +0,0 @@ -# Error handling and automatic retries in AWS Lambda - -When you invoke a function, two types of error can occur\. Invocation errors occur when the invocation request is rejected before your function receives it\. Function errors occur when your function's code or [runtime](lambda-runtimes.md) returns an error\. Depending on the type of error, the type of invocation, and the client or service that invokes the function, the retry behavior and the strategy for managing errors varies\. - -Issues with the request, caller, or account can cause invocation errors\. Invocation errors include an error type and status code in the response that indicate the cause of the error\. - -**Common invocation errors** -+ **Request** – The request event is too large or isn't valid JSON, the function doesn't exist, or a parameter value is the wrong type\. -+ **Caller** – The user or service doesn't have permission to invoke the function\. -+ **Account** – The maximum number of function instances are already running, or requests are being made too quickly\. - -Clients such as the AWS CLI and the AWS SDK retry on client timeouts, throttling errors \(429\), and other errors that aren't caused by a bad request \(500 series\)\. For a full list of invocation errors, see [Invoke](API_Invoke.md)\. - -Function errors occur when your function code or the runtime that it uses return an error\. - -**Common function errors** -+ **Function** – Your function's code throws an exception or returns an error object\. -+ **Runtime** – The runtime terminated your function because it ran out of time, detected a syntax error, or failed to marshal the response object into JSON\. The function exited with an error code\. - -Unlike invocation errors, function errors don't cause Lambda to return a 400\-series or 500\-series status code\. If the function returns an error, Lambda indicates this by including a header named `X-Amz-Function-Error`, and a JSON\-formatted response with the error message and other details\. For examples of function errors in each language, see the following topics\. -+ [AWS Lambda function errors in Node\.js](nodejs-exceptions.md) -+ [AWS Lambda function errors in Python](python-exceptions.md) -+ [AWS Lambda function errors in Ruby](ruby-exceptions.md) -+ [AWS Lambda function errors in Java](java-exceptions.md) -+ [AWS Lambda function errors in Go](golang-exceptions.md) -+ [AWS Lambda function errors in C\#](csharp-exceptions.md) -+ [AWS Lambda function errors in PowerShell](powershell-exceptions.md) - -When you invoke a function directly, you determine the strategy for handling errors\. You can retry, send the event to a queue for debugging, or ignore the error\. Your function's code might have run completely, partially, or not at all\. If you retry, ensure that your function's code can handle the same event multiple times without causing duplicate transactions or other unwanted side effects\. - -When you invoke a function indirectly, you need to be aware of the retry behavior of the invoker and any service that the request encounters along the way\. This includes the following scenarios\. -+ **Asynchronous invocation** – Lambda retries function errors twice\. If the function doesn't have enough capacity to handle all incoming requests, events might wait in the queue for hours or days to be sent to the function\. You can configure a dead\-letter queue on the function to capture events that weren't successfully processed\. For more information, see [Asynchronous invocation](invocation-async.md)\. -+ **Event source mappings** – Event source mappings that read from streams retry the entire batch of items\. Repeated errors block processing of the affected shard until the error is resolved or the items expire\. To detect stalled shards, you can monitor the [Iterator Age](monitoring-metrics.md) metric\. - - For event source mappings that read from a queue, you determine the length of time between retries and destination for failed events by configuring the visibility timeout and redrive policy on the source queue\. For more information, see [AWS Lambda event source mappings](invocation-eventsourcemapping.md) and the service\-specific topics under [Using AWS Lambda with other services](lambda-services.md)\. -+ **AWS services** – AWS services can invoke your function [synchronously](invocation-sync.md) or asynchronously\. For synchronous invocation, the service decides whether to retry\. Services like API Gateway and Elastic Load Balancing, which proxy requests from an upstream user or client, can also choose to relay the error response back to the requestor\. - - For asynchronous invocation, the behavior is the same as when you invoke the function asynchronously\. For more information, see the service\-specific topics under [Using AWS Lambda with other services](lambda-services.md) and the invoking service's documentation\. -+ **Other accounts and clients** – When you grant access to other accounts, you can use [resource\-based policies](access-control-resource-based.md) to restrict the services or resources they can configure to invoke your function\. To protect your function from being overloaded, consider putting an API layer in front of your function with [Amazon API Gateway](services-apigateway.md)\. - -To help you deal with errors in Lambda applications, Lambda integrates with services like Amazon CloudWatch and AWS X\-Ray\. You can use a combination of logs, metrics, alarms, and tracing to quickly detect and identify issues in your function code, API, or other resources that support your application\. For more information, see [Monitoring and troubleshooting Lambda applications](lambda-monitoring.md)\. - -For a sample application that uses a CloudWatch Logs subscription, X\-Ray tracing, and a Lambda function to detect and process errors, see [Error processor sample application for AWS Lambda](samples-errorprocessor.md)\. \ No newline at end of file diff --git a/doc_source/invocation-scaling.md b/doc_source/invocation-scaling.md deleted file mode 100644 index 9c0511bd..00000000 --- a/doc_source/invocation-scaling.md +++ /dev/null @@ -1,67 +0,0 @@ -# AWS Lambda function scaling - -The first time you invoke your function, AWS Lambda creates an instance of the function and runs its handler method to process the event\. When the function returns a response, it stays active and waits to process additional events\. If you invoke the function again while the first event is being processed, Lambda initializes another instance, and the function processes the two events concurrently\. As more events come in, Lambda routes them to available instances and creates new instances as needed\. When the number of requests decreases, Lambda stops unused instances to free up scaling capacity for other functions\. - - Your functions' *concurrency* is the number of instances that serve requests at a given time\. For an initial burst of traffic, your functions' cumulative concurrency in a Region can reach an initial level of between 500 and 3000, which varies per Region\. - -**Burst concurrency limits** -+ **3000** – US West \(Oregon\), US East \(N\. Virginia\), Europe \(Ireland\) -+ **1000** – Asia Pacific \(Tokyo\), Europe \(Frankfurt\) -+ **500** – Other Regions - -After the initial burst, your functions' concurrency can scale by an additional 500 instances each minute\. This continues until there are enough instances to serve all requests, or until a concurrency limit is reached\. When requests come in faster than your function can scale, or when your function is at maximum concurrency, additional requests fail with a throttling error \(429 status code\)\. - -The following example shows a function processing a spike in traffic\. As invocations increase exponentially, the function scales up\. It initializes a new instance for any request that can't be routed to an available instance\. When the burst concurrency limit is reached, the function starts to scale linearly\. If this isn't enough concurrency to serve all requests, additional requests are throttled and should be retried\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-scaling.png) - -**Legend** -+ ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-scaling-provisioned.instances.png) Function instances -+ ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-scaling-provisioned.open.png) Open requests -+ ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-scaling.throttling.png) Throttling possible - -The function continues to scale until the account's concurrency limit for the function's Region is reached\. The function catches up to demand, requests subside, and unused instances of the function are stopped after being idle for some time\. Unused instances are frozen while they're waiting for requests and don't incur any charges\. - -The regional concurrency limit starts at 1,000\. You can increase the limit by submitting a request in the [Support Center console](https://console.aws.amazon.com/support/v1#/case/create?issueType=service-limit-increase)\. To allocate capacity on a per\-function basis, you can configure functions with [reserved concurrency](configuration-concurrency.md)\. Reserved concurrency creates a pool that can only be used by its function, and also prevents its function from using unreserved concurrency\. - -When your function scales up, the first request served by each instance is impacted by the time it takes to load and initialize your code\. If your [initialization code](gettingstarted-features.md#gettingstarted-features-programmingmodel) takes a long time, the impact on average and percentile latency can be significant\. To enable your function to scale without fluctuations in latency, use [provisioned concurrency](configuration-concurrency.md)\. The following example shows a function with provisioned concurrency processing a spike in traffic\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-scaling-provisioned.png) - -**Legend** -+ ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-scaling-provisioned.instances.png) Function instances -+ ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-scaling-provisioned.open.png) Open requests -+ ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-scaling-provisioned.provisioned.png) Provisioned concurrency -+ ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-scaling-provisioned.standard.png) Standard concurrency - -When provisioned concurrency is allocated, the function scales with the same burst behavior as standard concurrency\. After it's allocated, provisioned concurrency serves incoming requests with very low latency\. When all provisioned concurrency is in use, the function scales up normally to handle any additional requests\. - -Application Auto Scaling takes this a step further by providing autoscaling for provisioned concurrency\. With Application Auto Scaling, you can create a target tracking scaling policy that adjusts provisioned concurrency levels automatically, based on the utilization metric that Lambda emits\. [Use the Application Auto Scaling API](configuration-concurrency.md#configuration-concurrency-api) to register an alias as a scalable target and create a scaling policy\. - -In the following example, a function scales between a minimum and maximum amount of provisioned concurrency based on utilization\. When the number of open requests increases, Application Auto Scaling increases provisioned concurrency in large steps until it reaches the configured maximum\. The function continues to scale on standard concurrency until utilization starts to drop\. When utilization is consistently low, Application Auto Scaling decreases provisioned concurrency in smaller periodic steps\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-scaling-provisioned-auto.png) - -**Legend** -+ ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-scaling-provisioned.instances.png) Function instances -+ ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-scaling-provisioned.open.png) Open requests -+ ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-scaling-provisioned.provisioned.png) Provisioned concurrency -+ ![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/features-scaling-provisioned.standard.png) Standard concurrency - -When you invoke your function asynchronously, by using an event source mapping or another AWS service, scaling behavior varies\. For example, event source mappings that read from a stream are limited by the number of shards in the stream\. Scaling capacity that is unused by an event source is available for use by other clients and event sources\. For more information, see the following topics\. -+ [Asynchronous invocation](invocation-async.md) -+ [AWS Lambda event source mappings](invocation-eventsourcemapping.md) -+ [Error handling and automatic retries in AWS Lambda](invocation-retries.md) -+ [Using AWS Lambda with other services](lambda-services.md) - -You can monitor concurrency levels in your account by using the following metrics: - -**Concurrency metrics** -+ `ConcurrentExecutions` -+ `UnreservedConcurrentExecutions` -+ `ProvisionedConcurrentExecutions` -+ `ProvisionedConcurrencyInvocations` -+ `ProvisionedConcurrencySpilloverInvocations` -+ `ProvisionedConcurrencyUtilization` - -For more information, see [Working with AWS Lambda function metrics](monitoring-metrics.md)\. \ No newline at end of file diff --git a/doc_source/invocation-sync.md b/doc_source/invocation-sync.md deleted file mode 100644 index 5692e547..00000000 --- a/doc_source/invocation-sync.md +++ /dev/null @@ -1,58 +0,0 @@ -# Synchronous invocation - -When you invoke a function synchronously, Lambda runs the function and waits for a response\. When the function execution ends, Lambda returns the response from the function's code with additional data, such as the version of the function that was executed\. To invoke a function synchronously with the AWS CLI, use the `invoke` command\. - -``` -$ aws lambda invoke --function-name my-function --payload '{ "key": "value" }' response.json -{ - "ExecutedVersion": "$LATEST", - "StatusCode": 200 -} -``` - -The following diagram shows clients invoking a Lambda function synchronously\. Lambda sends the events directly to the function and sends the function's response back to the invoker\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/invocation-sync.png) - -The `payload` is a string that contains an event in JSON format\. The name of the file where the AWS CLI writes the response from the function is `response.json`\. If the function returns an object or error, the response is the object or error in JSON format\. If the function exits without error, the response is `null`\. - -The output from the command, which is displayed in the terminal, includes information from headers in the response from Lambda\. This includes the version that processed the event \(useful when you use [aliases](configuration-aliases.md)\), and the status code returned by Lambda\. If Lambda was able to run the function, the status code is 200, even if the function returned an error\. - -**Note** -For functions with a long timeout, your client might be disconnected during synchronous invocation while it waits for a response\. Configure your HTTP client, SDK, firewall, proxy, or operating system to allow for long connections with timeout or keep\-alive settings\. - -If Lambda isn't able to run the function, the error is displayed in the output\. - -``` -$ aws lambda invoke --function-name my-function --payload value response.json -An error occurred (InvalidRequestContentException) when calling the Invoke operation: Could not parse request body into json: Unrecognized token 'value': was expecting ('true', 'false' or 'null') - at [Source: (byte[])"value"; line: 1, column: 11] -``` - -To get logs for an invocation from the command line, use the `--log-type` option\. The response includes a `LogResult` field that contains up to 4 KB of base64\-encoded logs from the invocation\. - -``` -$ aws lambda invoke --function-name my-function out --log-type Tail -{ - "StatusCode": 200, - "LogResult": "U1RBUlQgUmVxdWVzdElkOiA4N2QwNDRiOC1mMTU0LTExZTgtOGNkYS0yOTc0YzVlNGZiMjEgVmVyc2lvb...", - "ExecutedVersion": "$LATEST" -} -``` - -You can use the `base64` utility to decode the logs\. - -``` -$ aws lambda invoke --function-name my-function out --log-type Tail \ ---query 'LogResult' --output text | base64 -d -START RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 Version: $LATEST - "AWS_SESSION_TOKEN": "AgoJb3JpZ2luX2VjELj...", "_X_AMZN_TRACE_ID": "Root=1-5d02e5ca-f5792818b6fe8368e5b51d50;Parent=191db58857df8395;Sampled=0"",ask/lib:/opt/lib", -END RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 -REPORT RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 Duration: 79.67 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 73 MB -``` - -The `base64` utility is available on Linux, macOS, and [Ubuntu on Windows](https://docs.microsoft.com/en-us/windows/wsl/install-win10)\. For macOS, the command is `base64 -D`\. - -For more information about the `Invoke` API, including a full list of parameters, headers, and errors, see [Invoke](API_Invoke.md)\. - -When you invoke a function directly, you can check the response for errors and retry\. The AWS CLI and AWS SDK also automatically retry on client timeouts, throttling, and service errors\. For more information, see [Error handling and automatic retries in AWS Lambda](invocation-retries.md)\. \ No newline at end of file diff --git a/doc_source/java-context.md b/doc_source/java-context.md deleted file mode 100644 index 12cc6f36..00000000 --- a/doc_source/java-context.md +++ /dev/null @@ -1,108 +0,0 @@ -# AWS Lambda context object in Java - -When Lambda runs your function, it passes a context object to the [handler](java-handler.md)\. This object provides methods and properties that provide information about the invocation, function, and execution environment\. - -**Context methods** -+ `getRemainingTimeInMillis()` – Returns the number of milliseconds left before the execution times out\. -+ `getFunctionName()` – Returns the name of the Lambda function\. -+ `getFunctionVersion()` – Returns the [version](configuration-versions.md) of the function\. -+ `getInvokedFunctionArn()` – Returns the Amazon Resource Name \(ARN\) that's used to invoke the function\. Indicates if the invoker specified a version number or alias\. -+ `getMemoryLimitInMB()` – Returns the amount of memory that's allocated for the function\. -+ `getAwsRequestId()` – Returns the identifier of the invocation request\. -+ `getLogGroupName()` – Returns the log group for the function\. -+ `getLogStreamName()` – Returns the log stream for the function instance\. -+ `getIdentity()` – \(mobile apps\) Returns information about the Amazon Cognito identity that authorized the request\. -+ `getClientContext()` – \(mobile apps\) Returns the client context that's provided to Lambda by the client application\. -+ `getLogger()` – Returns the [logger object](java-logging.md) for the function\. - -The following example shows a function that uses the context object to access the Lambda logger\. - -**Example [Handler\.java](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/java-basic/src/main/java/example/Handler.java)** - -``` -package example; -import [com\.amazonaws\.services\.lambda\.runtime\.Context](https://github.com/aws/aws-lambda-java-libs/blob/master/aws-lambda-java-core/src/main/java/com/amazonaws/services/lambda/runtime/Context.java) -import [com\.amazonaws\.services\.lambda\.runtime\.RequestHandler](https://github.com/aws/aws-lambda-java-libs/blob/master/aws-lambda-java-core/src/main/java/com/amazonaws/services/lambda/runtime/RequestHandler.java) -import [com\.amazonaws\.services\.lambda\.runtime\.LambdaLogger](https://github.com/aws/aws-lambda-java-libs/blob/master/aws-lambda-java-core/src/main/java/com/amazonaws/services/lambda/runtime/LambdaLogger.java) -... - -// Handler value: example.Handler -public class Handler implements RequestHandler, String>{ - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - @Override - public String handleRequest(Map event, Context context) - { - LambdaLogger logger = context.getLogger(); - String response = new String("200 OK"); - // log execution details - logger.log("ENVIRONMENT VARIABLES: " + gson.toJson(System.getenv())); - logger.log("CONTEXT: " + gson.toJson(context)); - // process event - logger.log("EVENT: " + gson.toJson(event)); - logger.log("EVENT TYPE: " + event.getClass().toString()); - return response; - } -} -``` - -The function serializes the context object into JSON and records it in its log stream\. - -**Example Log output** - -``` -START RequestId: 6bc28136-xmpl-4365-b021-0ce6b2e64ab0 Version: $LATEST -... -CONTEXT: -{ - "memoryLimit": 512, - "awsRequestId": "6bc28136-xmpl-4365-b021-0ce6b2e64ab0", - "functionName": "java-console", - ... -} -... -END RequestId: 6bc28136-xmpl-4365-b021-0ce6b2e64ab0 -REPORT RequestId: 6bc28136-xmpl-4365-b021-0ce6b2e64ab0 Duration: 198.50 ms Billed Duration: 200 ms Memory Size: 512 MB Max Memory Used: 90 MB Init Duration: 524.75 ms -``` - -The interface for the context object is available in the [aws\-lambda\-java\-core](https://github.com/aws/aws-lambda-java-libs/tree/master/aws-lambda-java-core) library\. You can implement this interface to create a context class for testing\. The following example shows a context class that returns dummy values for most properties and a working test logger\. - -**Example [src/test/java/example/TestContext\.java](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/java-basic/src/test/java/example/TestContext.java)** - -``` -package example; - -import [com\.amazonaws\.services\.lambda\.runtime\.Context](https://github.com/aws/aws-lambda-java-libs/blob/master/aws-lambda-java-core/src/main/java/com/amazonaws/services/lambda/runtime/Context.java); -import [com\.amazonaws\.services\.lambda\.runtime\.CognitoIdentity](https://github.com/aws/aws-lambda-java-libs/blob/master/aws-lambda-java-core/src/main/java/com/amazonaws/services/lambda/runtime/CognitoIdentity.java); -import [com\.amazonaws\.services\.lambda\.runtime\.ClientContext](https://github.com/aws/aws-lambda-java-libs/blob/master/aws-lambda-java-core/src/main/java/com/amazonaws/services/lambda/runtime/ClientContext.java); -import [com\.amazonaws\.services\.lambda\.runtime\.LambdaLogger](https://github.com/aws/aws-lambda-java-libs/blob/master/aws-lambda-java-core/src/main/java/com/amazonaws/services/lambda/runtime/LambdaLogger.java) - -public class TestContext implements Context{ - public TestContext() {} - public String getAwsRequestId(){ - return new String("495b12a8-xmpl-4eca-8168-160484189f99"); - } - public String getLogGroupName(){ - return new String("/aws/lambda/my-function"); - } - ... - public LambdaLogger getLogger(){ - return new TestLogger(); - } - -} -``` - -For more information on logging, see [AWS Lambda function logging in Java](java-logging.md)\. - -## Context in sample applications - -The GitHub repository for this guide includes sample applications that demonstrate the use of the context object\. Each sample application includes scripts for easy deployment and cleanup, an AWS Serverless Application Model \(AWS SAM\) template, and supporting resources\. - -**Sample Lambda applications in Java** -+ [blank\-java](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/blank-java) – A Java function that shows the use of Lambda's Java libraries, logging, environment variables, layers, AWS X\-Ray tracing, unit tests, and the AWS SDK\. -+ [java\-basic](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/java-basic) – A minimal Java function with unit tests and variable logging configuration\. -+ [java\-events](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/java-events) – A minimal Java function that uses the [aws\-lambda\-java\-events](java-package.md) library with event types that don't require the AWS SDK as a dependency, such as Amazon API Gateway\. -+ [java\-events\-v1sdk](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/java-events-v1sdk) – A Java function that uses the [aws\-lambda\-java\-events](java-package.md) library with event types that require the AWS SDK as a dependency \(Amazon Simple Storage Service, Amazon DynamoDB, and Amazon Kinesis\)\. -+ [s3\-java](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/s3-java) – A Java function that processes notification events from Amazon S3 and uses the Java Class Library \(JCL\) to create thumbnails from uploaded image files\. - -All of the sample applications have a test context class for unit tests\. The `java-basic` application shows you how to use the context object to get a logger\. It uses SLF4J and Log4J 2 to provide a logger that works for local unit tests\. \ No newline at end of file diff --git a/doc_source/java-exceptions.md b/doc_source/java-exceptions.md deleted file mode 100644 index 4e8abcd5..00000000 --- a/doc_source/java-exceptions.md +++ /dev/null @@ -1,227 +0,0 @@ -# AWS Lambda function errors in Java - -When your function raises an error, Lambda returns details about the error to the invoker\. The body of the response that Lambda returns contains a JSON document with the error name, error type, and an array of stack frames\. The client or service that invoked the function can handle the error or pass it along to an end user\. You can use custom exceptions to return helpful information to users for client errors\. - -**Example [src/main/java/example/HandlerDivide\.java](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/java-basic/src/main/java/example/HandlerDivide.java) – Runtime exception** - -``` -import java.util.List; - -// Handler value: example.HandlerDivide -public class HandlerDivide implements RequestHandler, Integer>{ - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - @Override - public Integer handleRequest(List event, Context context) - { - LambdaLogger logger = context.getLogger(); - // process event - if ( event.size() != 2 ) - { - throw new InputLengthException("Input must be an array that contains 2 numbers."); - } - int numerator = event.get(0); - int denominator = event.get(1); - logger.log("EVENT: " + gson.toJson(event)); - logger.log("EVENT TYPE: " + event.getClass().toString()); - return numerator/denominator; - } -} -``` - -When the function throws `InputLengthException`, the Java runtime serializes it into the following document\. - -**Example Error document \(whitespace added\)** - -``` -{ - "errorMessage":"Input must contain 2 numbers.", - "errorType":"java.lang.InputLengthException", - "stackTrace": [ - "example.HandlerDivide.handleRequest(HandlerDivide.java:23)", - "example.HandlerDivide.handleRequest(HandlerDivide.java:14)" - ] -} -``` - -In this example, [InputLengthException](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/java-basic/src/main/java/example/InputLengthException.java) is a `RuntimeException`\. The `RequestHandler` [interface](java-handler.md#java-handler-interfaces) does not allow checked exceptions\. The `RequestStreamHandler` interface supports throwing `IOException` errors\. - -The return statement in the previous example can also throw a runtime exception\. - -``` - return numerator/denominator; -``` - -This code can return an arithmetic error\. - -``` -{"errorMessage":"/ by zero","errorType":"java.lang.ArithmeticException","stackTrace":["example.HandlerDivide.handleRequest(HandlerDivide.java:28)","example.HandlerDivide.handleRequest(HandlerDivide.java:13)"]} -``` - -**Topics** -+ [Viewing error output](#java-exceptions-view) -+ [Understanding error types and sources](#java-exceptions-types) -+ [Error handling in clients](#java-exceptions-clients) -+ [Error handling in other AWS services](#java-exceptions-services) -+ [Error handling in sample applications](#java-exceptions-samples) - -## Viewing error output - -You can invoke your function with a test payload and view error output in the Lambda console, from the command line, or with the AWS SDK\. Error output is also captured in the function's execution logs and, when [tracing](java-tracing.md) is enabled, in AWS X\-Ray\. - -To view error output in the Lambda console, invoke it with a test event\. - -**To invoke a function in the Lambda console** - -1. Open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions)\. - -1. Choose a function\. - -1. Choose **Configure test events** from the drop\-down menu next to the **Test** button\. -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/console-test-config.png) - -1. Choose an **Event template** that matches the events that your function processes\. - -1. Enter a name for the test event and modify the event structure as needed\. - -1. Choose **Create**\. - -1. Choose **Test**\. - -The Lambda console invokes your function [synchronously](invocation-sync.md) and displays the result\. To see the response, logs, and other information, expand the **Details** section\. - -When you invoke the function from the command line, the AWS CLI splits the response into two documents\. To indicate that a function error occurred, the response displayed in the terminal includes a `FunctionError` field\. The response or error returned by the function is written to the output file\. - -``` -$ aws lambda invoke --function-name my-function out.json -{ - "StatusCode": 200, - "FunctionError": "Unhandled", - "ExecutedVersion": "$LATEST" -} -``` - -View the output file to see the error document\. - -``` -$ cat out.json -{"errorMessage":"Input must contain 2 numbers.","errorType":"java.lang.InputLengthException","stackTrace": ["example.HandlerDivide.handleRequest(HandlerDivide.java:23)","example.HandlerDivide.handleRequest(HandlerDivide.java:14)"]} -``` - -Lambda also records up to 256 KB of the error object in the function's logs\. To view logs when you invoke the function from the command line, use the `--log-type` option and decode the base64 string in the response\. - -``` -$ aws lambda invoke --function-name my-function --payload "[100,0]" out.json --log-type Tail \ ---query 'LogResult' --output text | base64 -d -START RequestId: 081f7522-xmpl-48e2-8f67-96686904bb4f Version: $LATEST -EVENT: [ - 100, - 0 -]EVENT TYPE: class java.util.ArrayList/ by zero: java.lang.ArithmeticException -java.lang.ArithmeticException: / by zero - at example.HandlerDivide.handleRequest(HandlerDivide.java:28) - at example.HandlerDivide.handleRequest(HandlerDivide.java:13) - -END RequestId: 081f7522-xmpl-48e2-8f67-96686904bb4f -REPORT RequestId: 081f7522-xmpl-48e2-8f67-96686904bb4f Duration: 4.20 ms Billed Duration: 100 ms Memory Size: 512 MB Max Memory Used: 95 MB -XRAY TraceId: 1-5e73162b-1919xmpl2592f4549e1c39be SegmentId: 3dadxmpl48126cb8 Sampled: true -``` - -For more information about logs, see [AWS Lambda function logging in Java](java-logging.md)\. - -## Understanding error types and sources - -When you invoke a function, multiple subsystems handle the request, event, output, and response\. Errors can come from the Lambda service \(invocation errors\), or from an instance of your function\. Function errors include exceptions returned by your handler code and exceptions returned by the Lambda runtime\. - -The Lambda service receives the invocation request and validates it\. It checks permissions, verifies that the event document is a valid JSON document, and checks parameter values\. If the Lambda service encounters an error, it returns an exception type, message, and HTTP status code that indicate the cause of the error\. - -**Note** -For a full list of errors that the `Invoke` API operation can return, see [Invoke Errors](API_Invoke.md#API_Invoke_Errors) in the Lambda API reference\. - -A `4xx` series error from the Lambda service indicates an error that the invoker can fix by modifying the request, requesting permission, or trying again\. A `5xx` series error indicates an issue with the Lambda service, or an issue with the function's configuration or resources\. These issues can't be addressed by the invoker, but the function's owner might be able to fix them\. - -If a request passes validation, Lambda sends it to an instance of the function\. The runtime converts the event document into an object and passes it to your handler code\. Errors can occur during this process if, for example, the name of your handler method doesn't match the function's configuration, or if the invocation times out before your handler code returns a response\. Lambda runtime errors are formatted like errors that your code returns, but they are returned by the runtime\. - -In the following example, the runtime fails to deserialize the event into an object\. The input is a valid JSON type, but it doesn't match the type expected by the handler method\. - -**Example Lambda runtime error** - -``` -{ - "errorMessage": "An error occurred during JSON parsing", - "errorType": "java.lang.RuntimeException", - "stackTrace": [], - "cause": { - "errorMessage": "com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of java.lang.Integer from String value '1000,10': not a valid Integer value\n at [Source: lambdainternal.util.NativeMemoryAsInputStream@35fc6dc4; line: 1, column: 1] (through reference chain: java.lang.Object[0])", - "errorType": "java.io.UncheckedIOException", - "stackTrace": [], - "cause": { - "errorMessage": "Can not construct instance of java.lang.Integer from String value '1000,10': not a valid Integer value\n at [Source: lambdainternal.util.NativeMemoryAsInputStream@35fc6dc4; line: 1, column: 1] (through reference chain: java.lang.Object[0])", - "errorType": "com.fasterxml.jackson.databind.exc.InvalidFormatException", - "stackTrace": [ - "com.fasterxml.jackson.databind.exc.InvalidFormatException.from(InvalidFormatException.java:55)", - "com.fasterxml.jackson.databind.DeserializationContext.weirdStringException(DeserializationContext.java:907)", - ... - ] - } - } -} -``` - -For Lambda runtime errors and other function errors, the Lambda service does not return an error code\. A `2xx` series status code indicates that the Lambda service accepted the request\. Instead of an error code, Lambda indicates the error by including the `X-Amz-Function-Error` header in the response\. - -For asynchronous invocation, events are queued before Lambda sends them to your function\. For valid requests, Lambda returns a success response immediately and adds the event to the queue\. Lambda then reads events from the queue and invokes the function\. If an error occurs, Lambda retries with behavior that varies depending on the type of error\. For more information, see [Asynchronous invocation](invocation-async.md)\. - -## Error handling in clients - -Clients that invoke Lambda functions can choose to handle errors or pass them on to the end user\. The correct error handling behavior depends on the type of application, the audience, and the source of the error\. For example, if an invocation fails with an error code `429` \(too many requests\), the AWS CLI retries up to 4 times before showing an error to the user\. - -``` -$ aws lambda invoke --function-name my-function out.json -An error occurred (TooManyRequestsException) when calling the Invoke operation (reached max retries: 4): Rate Exceeded. -``` - -For other invocation errors, the correct behavior depends on the response code\. `5xx` series errors can indicate a temporary condition that can be resolved without any action by the user\. A retry might or might not succeed\. `4xx` series errors other than `429` generally indicate an error with the request\. A retry is not likely to succeed\. - -For function errors, the client can process the error document and show the error message in a user\-friendly format\. A browser\-based application might show the error message and type, but omit the stack trace\. The AWS CLI saves the error object to the output file and displays a document generated from the response headers instead\. - -``` -$ aws lambda invoke --function-name my-function --payload '[1000]' out.json -{ - "StatusCode": 200, - "FunctionError": "Unhandled", - "ExecutedVersion": "$LATEST" -} -``` - -**Example out\.json** - -``` -{"errorMessage":"Input must be an array that contains 2 numbers.","errorType":"example.InputLengthException","stackTrace":["example.HandlerDivide.handleRequest(HandlerDivide.java:22)","example.HandlerDivide.handleRequest(HandlerDivide.java:13)"]} -``` - -## Error handling in other AWS services - -When an AWS service invokes your function, the service chooses the invocation type and retry behavior\. AWS services can invoke your function on a schedule, in response to a lifecycle event on a resource, or to serve a request from a user\. Some services invoke functions asynchronously and let Lambda handle errors, while others retry or pass errors back to the user\. - -For example, API Gateway treats all invocation and function errors as internal errors\. If the Lambda API rejects the invocation request, API Gateway returns a 500 error code\. If the function runs but returns an error, or returns a response in the wrong format, API Gateway returns a 502 error code\. To customize the error response, you must catch errors in your code and format a response in the required format\. - -To determine the source of an error and its cause, use AWS X\-Ray\. With X\-Ray, you can find out which component encountered an error and see details about exceptions\. The following example shows a function error that resulted in a 502 response from API Gateway\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/tracemap-apig-502.png) - -Get started with X\-Ray by [enabling active tracing](java-tracing.md) on your functions\. - -For details on how other services handler errors, see the topics in the [Using AWS Lambda with other services](lambda-services.md) chapter\. - -## Error handling in sample applications - -The GitHub repository for this guide includes sample applications that demonstrate the use of the errors\. Each sample application includes scripts for easy deployment and cleanup, an AWS Serverless Application Model \(AWS SAM\) template, and supporting resources\. - -**Sample Lambda applications in Java** -+ [blank\-java](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/blank-java) – A Java function that shows the use of Lambda's Java libraries, logging, environment variables, layers, AWS X\-Ray tracing, unit tests, and the AWS SDK\. -+ [java\-basic](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/java-basic) – A minimal Java function with unit tests and variable logging configuration\. -+ [java\-events](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/java-events) – A minimal Java function that uses the [aws\-lambda\-java\-events](java-package.md) library with event types that don't require the AWS SDK as a dependency, such as Amazon API Gateway\. -+ [java\-events\-v1sdk](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/java-events-v1sdk) – A Java function that uses the [aws\-lambda\-java\-events](java-package.md) library with event types that require the AWS SDK as a dependency \(Amazon Simple Storage Service, Amazon DynamoDB, and Amazon Kinesis\)\. -+ [s3\-java](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/s3-java) – A Java function that processes notification events from Amazon S3 and uses the Java Class Library \(JCL\) to create thumbnails from uploaded image files\. - -The `java-basic` function includes a handler \(`HandlerDivide`\) that returns a custom runtime exception\. The `HandlerStream` handler implements the `RequestStreamHandler` and can throw an `IOException` checked exception\. \ No newline at end of file diff --git a/doc_source/java-handler.md b/doc_source/java-handler.md deleted file mode 100644 index 207c584d..00000000 --- a/doc_source/java-handler.md +++ /dev/null @@ -1,187 +0,0 @@ -# AWS Lambda function handler in Java - -Your Lambda function's handler is the method in your function code that processes events\. When your function is invoked, Lambda runs the handler method\. When the handler exits or returns a response, it becomes available to handle another event\. - -In the following example, a class named `Handler` defines a handler method named `handleRequest`\. The handler method takes an event and context object as input and returns a string\. - -**Example [Handler\.java](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/java-basic/src/main/java/example/Handler.java)** - -``` -package example; -import [com\.amazonaws\.services\.lambda\.runtime\.Context](https://github.com/aws/aws-lambda-java-libs/blob/master/aws-lambda-java-core/src/main/java/com/amazonaws/services/lambda/runtime/Context.java) -import [com\.amazonaws\.services\.lambda\.runtime\.RequestHandler](https://github.com/aws/aws-lambda-java-libs/blob/master/aws-lambda-java-core/src/main/java/com/amazonaws/services/lambda/runtime/RequestHandler.java) -import [com\.amazonaws\.services\.lambda\.runtime\.LambdaLogger](https://github.com/aws/aws-lambda-java-libs/blob/master/aws-lambda-java-core/src/main/java/com/amazonaws/services/lambda/runtime/LambdaLogger.java) -... - -// Handler value: example.Handler -public class Handler implements RequestHandler, String>{ - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - @Override - public String handleRequest(Map event, Context context) - { - LambdaLogger logger = context.getLogger(); - String response = new String("200 OK"); - // log execution details - logger.log("ENVIRONMENT VARIABLES: " + gson.toJson(System.getenv())); - logger.log("CONTEXT: " + gson.toJson(context)); - // process event - logger.log("EVENT: " + gson.toJson(event)); - logger.log("EVENT TYPE: " + event.getClass().toString()); - return response; - } -} -``` - -The [Lambda runtime](lambda-runtimes.md) receives an event as a JSON\-formatted string and converts it into an object\. It passes the event object to your function handler along with a context object that provides details about the invocation and the function\. You tell the runtime which method to invoke by setting the handler parameter on your function's configuration\. - -**Handler formats** -+ `package.Class::method` – Full format\. For example: `example.Handler::handleRequest`\. -+ `package.Class` – Abbreviated format for functions that implement a [handler interface](#java-handler-interfaces)\. For example: `example.Handler`\. - -You can add [initialization code](gettingstarted-features.md#gettingstarted-features-programmingmodel) outside of your handler method to reuse resources across multiple invocations\. When the runtime loads your handler, it runs static code and the class constructor\. Resources that are created during initialization stay in memory between invocations, and can be reused by the handler thousands of times\. - -In the following example, the logger, serializer, and AWS SDK client are created when the function serves its first event\. Subsequent events served by the same function instance are much faster because those resources already exist\. - -**Example [Handler\.java](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/blank-java/src/main/java/example/Handler.java) – Initialization code** - -``` -// Handler value: example.Handler -public class Handler implements RequestHandler{ - private static final Logger logger = LoggerFactory.getLogger(Handler.class); - private static final Gson gson = new GsonBuilder().setPrettyPrinting().create(); - private static final LambdaAsyncClient lambdaClient = LambdaAsyncClient.create(); - ... - @Override - public String handleRequest(SQSEvent event, Context context) - { - String response = new String(); - // call Lambda API - logger.info("Getting account settings"); - CompletableFuture accountSettings = - lambdaClient.getAccountSettings(GetAccountSettingsRequest.builder().build()); - // log execution details - logger.info("ENVIRONMENT VARIABLES: " + gson.toJson(System.getenv())); - ... -``` - -The GitHub repo for this guide provides easy\-to\-deploy sample applications that demonstrate a variety of handler types\. For details, see the [end of this topic](#java-handler-samples)\. - -**Topics** -+ [Choosing input and output types](#java-handler-types) -+ [Handler interfaces](#java-handler-interfaces) -+ [Sample handler code](#java-handler-samples) - -## Choosing input and output types - -You specify the type of object that the event maps to in the handler method's signature\. In the preceding example, the Java runtime deserializes the event into a type that implements the `Map` interface\. String\-to\-string maps work for flat events like the following: - -**Example [Event\.json](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/java-basic/event.json) – Weather data** - -``` -{ - "temperatureK": 281, - "windKmh": -3, - "humidityPct": 0.55, - "pressureHPa": 1020 -} -``` - -However, the value of each field must be a string or number\. If the event includes a field that has an object as a value, the runtime can't deserialize it and returns an error\. - -Choose an input type that works with the event data that your function processes\. You can use a basic type, a generic type, or a well\-defined type\. - -**Input types** -+ `Integer`, `Long`, `Double`, etc\. – The event is a number with no additional formatting—for example, `3.5`\. The runtime converts the value into an object of the specified type\. -+ `String` – The event is a JSON string, including quotes—for example, `"My string."`\. The runtime converts the value \(without quotes\) into a `String` object\. -+ `Type`, `Map` etc\. – The event is a JSON object\. The runtime deserializes it into an object of the specified type or interface\. -+ `List`, `List`, `List`, etc\. – The event is a JSON array\. The runtime deserializes it into an object of the specified type or interface\. -+ `InputStream` – The event is any JSON type\. The runtime passes a byte stream of the document to the handler without modification\. You deserialize the input and write output to an output stream\. -+ Library type – For events sent by AWS services, use the types in the [aws\-lambda\-java\-events](java-package.md) library\. - -If you define your own input type, it should be a deserializable, mutable plain old Java object \(POJO\), with a default constructor and properties for each field in the event\. Keys in the event that don't map to a property as well as properties that aren't included in the event are dropped without error\. - -The output type can be an object or `void`\. The runtime serializes return values into text\. If the output is an object with fields, the runtime serializes it into a JSON document\. If it's a type that wraps a primitive value, the runtime returns a text representation of that value\. - -## Handler interfaces - -The [aws\-lambda\-java\-core](https://github.com/aws/aws-lambda-java-libs/tree/master/aws-lambda-java-core) library defines two interfaces for handler methods\. Use the provided interfaces to simplify handler configuration and validate the handler method signature at compile time\. - -**** -+ [com\.amazonaws\.services\.lambda\.runtime\.RequestHandler](https://github.com/aws/aws-lambda-java-libs/blob/master/aws-lambda-java-core/src/main/java/com/amazonaws/services/lambda/runtime/RequestHandler.java) -+ [com\.amazonaws\.services\.lambda\.runtime\.RequestStreamHandler](https://github.com/aws/aws-lambda-java-libs/blob/master/aws-lambda-java-core/src/main/java/com/amazonaws/services/lambda/runtime/RequestStreamHandler.java) - -The `RequestHandler` interface is a generic type that takes two parameters: the input type and the output type\. Both types must be objects\. When you use this interface, the Java runtime deserializes the event into an object with the input type, and serializes the output into text\. Use this interface when the built\-in serialization works with your input and output types\. - -**Example [Handler\.java](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/java-basic/src/main/java/example/Handler.java) – Handler interface** - -``` -// Handler value: example.Handler -public class Handler implements RequestHandler, String>{ - @Override - public String handleRequest(Map event, Context context) -``` - -To use your own serialization, implement the `RequestStreamHandler` interface\. With this interface, Lambda passes your handler an input stream and output stream\. The handler reads bytes from the input stream, writes to the output stream, and returns void\. - -The following example uses buffered reader and writer types to work with the input and output streams\. It uses the [Gson](https://github.com/google/gson) library for serialization and deserialization\. - -**Example [HandlerStream\.java](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/java-basic/src/main/java/example/HandlerStream.java)** - -``` -import [com\.amazonaws\.services\.lambda\.runtime\.Context](https://github.com/aws/aws-lambda-java-libs/blob/master/aws-lambda-java-core/src/main/java/com/amazonaws/services/lambda/runtime/Context.java) -import [com\.amazonaws\.services\.lambda\.runtime\.RequestStreamHandler](https://github.com/aws/aws-lambda-java-libs/blob/master/aws-lambda-java-core/src/main/java/com/amazonaws/services/lambda/runtime/RequestStreamHandler.java) -import [com\.amazonaws\.services\.lambda\.runtime\.LambdaLogger](https://github.com/aws/aws-lambda-java-libs/blob/master/aws-lambda-java-core/src/main/java/com/amazonaws/services/lambda/runtime/LambdaLogger.java) -... -// Handler value: example.HandlerStream -public class HandlerStream implements RequestStreamHandler { - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - @Override - public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException - { - LambdaLogger logger = context.getLogger(); - BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("US-ASCII"))); - PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream, Charset.forName("US-ASCII")))); - try - { - HashMap event = gson.fromJson(reader, HashMap.class); - logger.log("STREAM TYPE: " + inputStream.getClass().toString()); - logger.log("EVENT TYPE: " + event.getClass().toString()); - writer.write(gson.toJson(event)); - if (writer.checkError()) - { - logger.log("WARNING: Writer encountered an error."); - } - } - catch (IllegalStateException | JsonSyntaxException exception) - { - logger.log(exception.toString()); - } - finally - { - reader.close(); - writer.close(); - } - } -} -``` - -## Sample handler code - -The GitHub repository for this guide includes sample applications that demonstrate the use of various handler types and interfaces\. Each sample application includes scripts for easy deployment and cleanup, an AWS SAM template, and supporting resources\. - -**Sample Lambda applications in Java** -+ [blank\-java](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/blank-java) – A Java function that shows the use of Lambda's Java libraries, logging, environment variables, layers, AWS X\-Ray tracing, unit tests, and the AWS SDK\. -+ [java\-basic](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/java-basic) – A minimal Java function with unit tests and variable logging configuration\. -+ [java\-events](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/java-events) – A minimal Java function that uses the [aws\-lambda\-java\-events](java-package.md) library with event types that don't require the AWS SDK as a dependency, such as Amazon API Gateway\. -+ [java\-events\-v1sdk](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/java-events-v1sdk) – A Java function that uses the [aws\-lambda\-java\-events](java-package.md) library with event types that require the AWS SDK as a dependency \(Amazon Simple Storage Service, Amazon DynamoDB, and Amazon Kinesis\)\. -+ [s3\-java](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/s3-java) – A Java function that processes notification events from Amazon S3 and uses the Java Class Library \(JCL\) to create thumbnails from uploaded image files\. - -The `blank-java` and `s3-java` applications take an AWS service event as input and return a string\. The `java-basic` application includes several types of handlers: -+ [Handler\.java](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/java-basic/src/main/java/example/Handler.java) – Takes a `Map` as input\. -+ [HandlerInteger\.java](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/java-basic/src/main/java/example/HandlerInteger.java) – Takes an `Integer` as input\. -+ [HandlerList\.java](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/java-basic/src/main/java/example/HandlerList.java) – Takes a `List` as input\. -+ [HandlerStream\.java](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/java-basic/src/main/java/example/HandlerStream.java) – Takes an `InputStream` and `OutputStream` as input\. -+ [HandlerString\.java](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/java-basic/src/main/java/example/HandlerString.java) – Takes a `String` as input\. -+ [HandlerWeatherData\.java](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/java-basic/src/main/java/example/HandlerWeatherData.java) – Takes a custom type as input\. - -To test different handler types, just change the handler value in the AWS SAM template\. For detailed instructions, see the sample application's readme file\. \ No newline at end of file diff --git a/doc_source/java-logging.md b/doc_source/java-logging.md deleted file mode 100644 index 01f6d51a..00000000 --- a/doc_source/java-logging.md +++ /dev/null @@ -1,300 +0,0 @@ -# AWS Lambda function logging in Java - -Your Lambda function comes with a CloudWatch Logs log group, with a log stream for each instance of your function\. The runtime sends details about each invocation to the log stream, and relays logs and other output from your function's code\. - -To output logs from your function code, you can use methods on [java\.lang\.System](https://docs.oracle.com/javase/8/docs/api/java/lang/System.html), or any logging module that writes to `stdout` or `stderr`\. The [aws\-lambda\-java\-core](java-package.md) library provides a logger class named `LambdaLogger` that you can access from the context object\. The logger class supports multiline logs\. - -The following example uses the `LambdaLogger` logger provided by the context object\. - -**Example Handler\.java** - -``` -// Handler value: example.Handler -public class Handler implements RequestHandler{ - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - @Override - public String handleRequest(Object event, Context context) - { - LambdaLogger logger = context.getLogger(); - String response = new String("SUCCESS"); - // log execution details - logger.log("ENVIRONMENT VARIABLES: " + gson.toJson(System.getenv())); - logger.log("CONTEXT: " + gson.toJson(context)); - // process event - logger.log("EVENT: " + gson.toJson(event)); - return response; - } -} -``` - -**Example Log format** - -``` -START RequestId: 6bc28136-xmpl-4365-b021-0ce6b2e64ab0 Version: $LATEST -ENVIRONMENT VARIABLES: -{ - "_HANDLER": "example.Handler", - "AWS_EXECUTION_ENV": "AWS_Lambda_java8", - "AWS_LAMBDA_FUNCTION_MEMORY_SIZE": "512", - ... -} -CONTEXT: -{ - "memoryLimit": 512, - "awsRequestId": "6bc28136-xmpl-4365-b021-0ce6b2e64ab0", - "functionName": "java-console", - ... -} -EVENT: -{ - "records": [ - { - "messageId": "19dd0b57-xmpl-4ac1-bd88-01bbb068cb78", - "receiptHandle": "MessageReceiptHandle", - "body": "Hello from SQS!", - ... - } - ] -} -END RequestId: 6bc28136-xmpl-4365-b021-0ce6b2e64ab0 -REPORT RequestId: 6bc28136-xmpl-4365-b021-0ce6b2e64ab0 Duration: 198.50 ms Billed Duration: 200 ms Memory Size: 512 MB Max Memory Used: 90 MB Init Duration: 524.75 ms -``` - -The Java runtime logs the `START`, `END`, and `REPORT` lines for each invocation\. The report line provides the following details: - -**Report Log** -+ **RequestId** – The unique request ID for the invocation\. -+ **Duration** – The amount of time that your function's handler method spent processing the event\. -+ **Billed Duration** – The amount of time billed for the invocation\. -+ **Memory Size** – The amount of memory allocated to the function\. -+ **Max Memory Used** – The amount of memory used by the function\. -+ **Init Duration** – For the first request served, the amount of time it took the runtime to load the function and run code outside of the handler method\. -+ **XRAY TraceId** – For traced requests, the [AWS X\-Ray trace ID](lambda-x-ray.md)\. -+ **SegmentId** – For traced requests, the X\-Ray segment ID\. -+ **Sampled** – For traced requests, the sampling result\. - -You can view logs in the Lambda console, in the CloudWatch Logs console, or from the command line\. - -**Topics** -+ [Viewing logs in the AWS Management Console](#java-logging-console) -+ [Using the AWS CLI](#java-logging-cli) -+ [Deleting logs](#java-logging-delete) -+ [Advanced logging with Log4j 2 and SLF4J](#java-logging-log4j2) -+ [Sample logging code](#java-logging-samples) - -## Viewing logs in the AWS Management Console - -The Lambda console shows log output when you test a function on the function configuration page\. To view logs for all invocations, use the CloudWatch Logs console\. - -**To view your Lambda function's logs** - -1. Open the [Logs page of the CloudWatch console](https://console.aws.amazon.com/cloudwatch/home?#logs:)\. - -1. Choose the log group for your function \(**/aws/lambda/*function\-name***\)\. - -1. Choose the first stream in the list\. - -Each log stream corresponds to an [instance of your function](runtimes-context.md)\. New streams appear when you update your function and when additional instances are created to handle multiple concurrent invocations\. To find logs for specific invocations, you can instrument your function with X\-Ray, and record details about the request and log stream in the trace\. For a sample application that correlates logs and traces with X\-Ray, see [Error processor sample application for AWS Lambda](samples-errorprocessor.md)\. - -## Using the AWS CLI - -To get logs for an invocation from the command line, use the `--log-type` option\. The response includes a `LogResult` field that contains up to 4 KB of base64\-encoded logs from the invocation\. - -``` -$ aws lambda invoke --function-name my-function out --log-type Tail -{ - "StatusCode": 200, - "LogResult": "U1RBUlQgUmVxdWVzdElkOiA4N2QwNDRiOC1mMTU0LTExZTgtOGNkYS0yOTc0YzVlNGZiMjEgVmVyc2lvb...", - "ExecutedVersion": "$LATEST" -} -``` - -You can use the `base64` utility to decode the logs\. - -``` -$ aws lambda invoke --function-name my-function out --log-type Tail \ ---query 'LogResult' --output text | base64 -d -START RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 Version: $LATEST - "AWS_SESSION_TOKEN": "AgoJb3JpZ2luX2VjELj...", "_X_AMZN_TRACE_ID": "Root=1-5d02e5ca-f5792818b6fe8368e5b51d50;Parent=191db58857df8395;Sampled=0"",ask/lib:/opt/lib", -END RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 -REPORT RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 Duration: 79.67 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 73 MB -``` - -The `base64` utility is available on Linux, macOS, and [Ubuntu on Windows](https://docs.microsoft.com/en-us/windows/wsl/install-win10)\. For macOS, the command is `base64 -D`\. - -To get full log events from the command line, you can include the log stream name in the output of your function, as shown in the preceding example\. The following example script invokes a function named `my-function` and downloads the last five log events\. - -**Example get\-logs\.sh Script** -This example requires that `my-function` returns a log stream ID\. - -``` -#!/bin/bash -aws lambda invoke --function-name my-function --payload '{"key": "value"}' out -sed -i'' -e 's/"//g' out -sleep 15 -aws logs get-log-events --log-group-name /aws/lambda/my-function --log-stream-name $(cat out) --limit 5 -``` - -The script uses `sed` to remove quotes from the output file, and sleeps for 15 seconds to allow time for the logs to be available\. The output includes the response from Lambda and the output from the `get-log-events` command\. - -``` -$ ./get-logs.sh -{ - "StatusCode": 200, - "ExecutedVersion": "$LATEST" -} -{ - "events": [ - { - "timestamp": 1559763003171, - "message": "START RequestId: 4ce9340a-b765-490f-ad8a-02ab3415e2bf Version: $LATEST\n", - "ingestionTime": 1559763003309 - }, - { - "timestamp": 1559763003173, - "message": "2019-06-05T19:30:03.173Z\t4ce9340a-b765-490f-ad8a-02ab3415e2bf\tINFO\tENVIRONMENT VARIABLES\r{\r \"AWS_LAMBDA_FUNCTION_VERSION\": \"$LATEST\",\r ...", - "ingestionTime": 1559763018353 - }, - { - "timestamp": 1559763003173, - "message": "2019-06-05T19:30:03.173Z\t4ce9340a-b765-490f-ad8a-02ab3415e2bf\tINFO\tEVENT\r{\r \"key\": \"value\"\r}\n", - "ingestionTime": 1559763018353 - }, - { - "timestamp": 1559763003218, - "message": "END RequestId: 4ce9340a-b765-490f-ad8a-02ab3415e2bf\n", - "ingestionTime": 1559763018353 - }, - { - "timestamp": 1559763003218, - "message": "REPORT RequestId: 4ce9340a-b765-490f-ad8a-02ab3415e2bf\tDuration: 26.73 ms\tBilled Duration: 100 ms \tMemory Size: 128 MB\tMax Memory Used: 75 MB\t\n", - "ingestionTime": 1559763018353 - } - ], - "nextForwardToken": "f/34783877304859518393868359594929986069206639495374241795", - "nextBackwardToken": "b/34783877303811383369537420289090800615709599058929582080" -} -``` - -## Deleting logs - -Log groups aren't deleted automatically when you delete a function\. To avoid storing logs indefinitely, delete the log group, or [configure a retention period](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Working-with-log-groups-and-streams.html#SettingLogRetention) after which logs are deleted automatically\. - -## Advanced logging with Log4j 2 and SLF4J - -To customize log output, support logging during unit tests, and log AWS SDK calls, use Apache Log4j 2 with SLF4J\. Log4j is a logging library for Java programs that enables you to configure log levels and use appender libraries\. SLF4J is a facade library that lets you change which library you use without changing your function code\. - -To add the request ID to your function's logs, use the appender in the [aws\-lambda\-java\-log4j2](java-package.md) library\. The following example shows a Log4j 2 configuration file that adds a timestamp and request ID to all logs\. - -**Example [src/main/resources/log4j2\.xml](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/blank-java/src/main/resources/log4j2.xml) – Appender configuration** - -``` - - - - - %d{yyyy-MM-dd HH:mm:ss} %X{AWSRequestId} %-5p %c{1} - %m%n - - - - - - - - - - - -``` - -With this configuration, each line is prepended with the date, time, request ID, log level, and class name\. - -**Example Log format with appender** - -``` -START RequestId: 6bc28136-xmpl-4365-b021-0ce6b2e64ab0 Version: $LATEST -2020-03-18 08:52:43 6bc28136-xmpl-4365-b021-0ce6b2e64ab0 INFO Handler - ENVIRONMENT VARIABLES: -{ - "_HANDLER": "example.Handler", - "AWS_EXECUTION_ENV": "AWS_Lambda_java8", - "AWS_LAMBDA_FUNCTION_MEMORY_SIZE": "512", - ... -} -2020-03-18 08:52:43 6bc28136-xmpl-4365-b021-0ce6b2e64ab0 INFO Handler - CONTEXT: -{ - "memoryLimit": 512, - "awsRequestId": "6bc28136-xmpl-4365-b021-0ce6b2e64ab0", - "functionName": "java-console", - ... -} -``` - -SLF4J is a facade library for logging in Java code\. In your function code, you use the SLF4J logger factory to retrieve a logger with methods for log levels like `info()` and `warn()`\. In your build configuration, you include the logging library and SLF4J adapter in the classpath\. By changing the libraries in the build configuration, you can change the logger type without changing your function code\. SLF4J is required to capture logs from the SDK for Java\. - -In the following example, the handler class uses SLF4J to retrieve a logger\. - -**Example [src/main/java/example/Handler\.java](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/blank-java/src/main/java/example/Handler.java) – Logging with SLF4J** - -``` -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -// Handler value: example.Handler -public class Handler implements RequestHandler{ - private static final Logger logger = LoggerFactory.getLogger(Handler.class); - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - LambdaAsyncClient lambdaClient = LambdaAsyncClient.create(); - @Override - public String handleRequest(SQSEvent event, Context context) - { - String response = new String(); - // call Lambda API - logger.info("Getting account settings"); - CompletableFuture accountSettings = - lambdaClient.getAccountSettings(GetAccountSettingsRequest.builder().build()); - // log execution details - logger.info("ENVIRONMENT VARIABLES: {}", gson.toJson(System.getenv())); -... -``` - -The build configuration takes runtime dependencies on the Lambda appender and SLF4J adapter, and implementation dependencies on Log4J 2\. - -**Example [build\.gradle](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/blank-java/build.gradle) – Logging dependencies** - -``` -dependencies { - implementation platform('software.amazon.awssdk:bom:2.10.73') - implementation platform('com.amazonaws:aws-xray-recorder-sdk-bom:2.4.0') - implementation 'software.amazon.awssdk:lambda' - implementation 'com.amazonaws:aws-xray-recorder-sdk-core' - implementation 'com.amazonaws:aws-xray-recorder-sdk-aws-sdk-core' - implementation 'com.amazonaws:aws-xray-recorder-sdk-aws-sdk-v2' - implementation 'com.amazonaws:aws-xray-recorder-sdk-aws-sdk-v2-instrumentor' - implementation 'com.amazonaws:aws-lambda-java-core:1.2.0' - implementation 'com.amazonaws:aws-lambda-java-events:2.2.7' - implementation 'com.google.code.gson:gson:2.8.6' - implementation 'org.apache.logging.log4j:log4j-api:2.13.0' - implementation 'org.apache.logging.log4j:log4j-core:2.13.0' - runtimeOnly 'org.apache.logging.log4j:log4j-slf4j18-impl:2.13.0' - runtimeOnly 'com.amazonaws:aws-lambda-java-log4j2:1.1.0' - testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0' - testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.6.0' -} -``` - -When you run your code locally for tests, the context object with the Lambda logger is not available, and there's no request ID for the Lambda appender to use\. For example test configurations, see the sample applications in the next section\. - -## Sample logging code - -The GitHub repository for this guide includes sample applications that demonstrate the use of various logging configurations\. Each sample application includes scripts for easy deployment and cleanup, an AWS SAM template, and supporting resources\. - -**Sample Lambda applications in Java** -+ [blank\-java](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/blank-java) – A Java function that shows the use of Lambda's Java libraries, logging, environment variables, layers, AWS X\-Ray tracing, unit tests, and the AWS SDK\. -+ [java\-basic](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/java-basic) – A minimal Java function with unit tests and variable logging configuration\. -+ [java\-events](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/java-events) – A minimal Java function that uses the [aws\-lambda\-java\-events](java-package.md) library with event types that don't require the AWS SDK as a dependency, such as Amazon API Gateway\. -+ [java\-events\-v1sdk](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/java-events-v1sdk) – A Java function that uses the [aws\-lambda\-java\-events](java-package.md) library with event types that require the AWS SDK as a dependency \(Amazon Simple Storage Service, Amazon DynamoDB, and Amazon Kinesis\)\. -+ [s3\-java](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/s3-java) – A Java function that processes notification events from Amazon S3 and uses the Java Class Library \(JCL\) to create thumbnails from uploaded image files\. - -The `java-basic` sample application shows a minimal logging configuration that supports logging tests\. The handler code uses the `LambdaLogger` logger provided by the context object\. For tests, the application uses a custom `TestLogger` class that implements the `LambdaLogger` interface with a Log4j 2 logger\. It uses SLF4J as a facade for compatibility with the AWS SDK\. Logging libraries are excluded from build output to keep the deployment package small\. - -The `blank-java` sample application builds on the basic configuration with AWS SDK logging and the Lambda Log4j 2 appender\. It uses Log4j 2 in Lambda with custom appender that adds the invocation request ID to each line\. \ No newline at end of file diff --git a/doc_source/java-package-eclipse.md b/doc_source/java-package-eclipse.md deleted file mode 100644 index e90c2a13..00000000 --- a/doc_source/java-package-eclipse.md +++ /dev/null @@ -1,98 +0,0 @@ -# Creating a deployment package using Eclipse - -This section shows how to package your Java code into a deployment package using Eclipse IDE and Maven plugin for Eclipse\. - -**Note** -The AWS SDK Eclipse Toolkit provides an Eclipse plugin for you to both create a deployment package and also upload it to create a Lambda function\. If you can use Eclipse IDE as your development environment, this plugin enables you to author Java code, create and upload a deployment package, and create your Lambda function\. For more information, see the [AWS Toolkit for Eclipse Getting Started Guide](https://docs.aws.amazon.com/AWSToolkitEclipse/latest/GettingStartedGuide/)\. For an example of using the toolkit for authoring Lambda functions, see [Using AWS Lambda with the AWS toolkit for Eclipse](https://docs.aws.amazon.com/AWSToolkitEclipse/latest/GettingStartedGuide/lambda.html)\. - -**Topics** -+ [Prerequisites](#java-package-eclipse-prereqs) -+ [Create and build a project](#java-package-eclipse-create) - -## Prerequisites - -Install the **Maven** Plugin for Eclipse\. - -1. Start Eclipse\. From the **Help** menu in Eclipse, choose **Install New Software**\. - -1. In the **Install** window, type **http://download\.eclipse\.org/technology/m2e/releases** in the **Work with:** box, and choose **Add**\. - -1. Follow the steps to complete the setup\. - -## Create and build a project - -In this step, you start Eclipse and create a Maven project\. You will add the necessary dependencies, and build the project\. The build will produce a \.jar, which is your deployment package\. - -1. Create a new Maven project in Eclipse\. - - 1. From the **File** menu, choose **New**, and then choose **Project**\. - - 1. In the **New Project** window, choose **Maven Project**\. - - 1. In the **New Maven Project** window, choose **Create a simple project**, and leave other default selections\. - - 1. In the **New Maven Project**, **Configure project** windows, type the following **Artifact** information: - + **Group Id**: doc\-examples - + **Artifact Id**: lambda\-java\-example - + **Version**: 0\.0\.1\-SNAPSHOT - + **Packaging**: jar - + **Name**: lambda\-java\-example - -1. Add the `aws-lambda-java-core` dependency to the `pom.xml` file\. - - It provides definitions of the `RequestHandler`, `RequestStreamHandler`, and `Context` interfaces\. This allows you to compile code that you can use with AWS Lambda\. - - 1. Open the context \(right\-click\) menu for the `pom.xml` file, choose **Maven**, and then choose **Add Dependency**\. - - 1. In the **Add Dependency** windows, type the following values: - - **Group Id:** com\.amazonaws - - **Artifact Id:** aws\-lambda\-java\-core - - **Version:** 1\.2\.0 -**Note** -If you are following other tutorial topics in this guide, the specific tutorials might require you to add more dependencies\. Make sure to add those dependencies as required\. - -1. Add Java class to the project\. - - 1. Open the context \(right\-click\) menu for the `src/main/java` subdirectory in the project, choose **New**, and then choose **Class**\. - - 1. In the **New Java Class** window, type the following values: - + **Package**: **example** - + **Name**: **Hello** -**Note** -If you are following other tutorial topics in this guide, the specific tutorials might recommend different package name or class name\. - - 1. Add your Java code\. If you are following other tutorial topics in this guide, add the provided code\. - -1. Build the project\. - - Open the context \(right\-click\) menu for the project in **Package Explorer**, choose **Run As**, and then choose **Maven Build \.\.\.**\. In the **Edit Configuration** window, type **package** in the **Goals** box\. -**Note** -The resulting \.jar, `lambda-java-example-0.0.1-SNAPSHOT.jar`, is not the final standalone \.jar that you can use as your deployment package\. In the next step, you add the Apache `maven-shade-plugin` to create the standalone \.jar\. For more information, go to [Apache Maven Shade plugin](https://maven.apache.org/plugins/maven-shade-plugin/)\. - -1. Add the `maven-shade-plugin` plugin and rebuild\. - - The maven\-shade\-plugin will take artifacts \(jars\) produced by the *package* goal \(produces customer code \.jar\), and created a standalone \.jar that contains the compiled customer code, and the resolved dependencies from the `pom.xml`\. - - 1. Open the context \(right\-click\) menu for the `pom.xml` file, choose **Maven**, and then choose **Add Plugin**\. - - 1. In the **Add Plugin** window, type the following values: - + **Group Id:** org\.apache\.maven\.plugins - + **Artifact Id:** maven\-shade\-plugin - + **Version:** 3\.2\.2 - - 1. Now build again\. - - This time we will create the jar as before, and then use the `maven-shade-plugin` to pull in dependencies to make the standalone \.jar\. - - 1. Open the context \(right\-click\) menu for the project, choose **Run As**, and then choose **Maven build \.\.\.**\. - - 1. In the **Edit Configuration** windows, type **package shade:shade** in the **Goals** box\. - - 1. Choose `Run`\. - - You can find the resulting standalone \.jar \(that is, your deployment package\), in the `/target `subdirectory\. - - Open the context \(right\-click\) menu for the `/target` subdirectory, choose **Show In**, choose **System Explorer**, and you will find the `lambda-java-example-0.0.1-SNAPSHOT.jar`\. \ No newline at end of file diff --git a/doc_source/java-package.md b/doc_source/java-package.md deleted file mode 100644 index 186f7b86..00000000 --- a/doc_source/java-package.md +++ /dev/null @@ -1,304 +0,0 @@ -# AWS Lambda deployment package in Java - -A deployment package is a ZIP archive that contains your compiled function code and dependencies\. You can upload the package directly to Lambda, or you can use an Amazon S3 bucket, and then upload it to Lambda\. If the deployment package is larger than 50 MB, you must use Amazon S3\. - -AWS Lambda provides the following libraries for Java functions: -+ [com\.amazonaws:aws\-lambda\-java\-core](https://github.com/aws/aws-lambda-java-libs/tree/master/aws-lambda-java-core) \(required\) – Defines handler method interfaces and the context object that the runtime passes to the handler\. If you define your own input types, this is the only library you need\. -+ [com\.amazonaws:aws\-lambda\-java\-events](https://github.com/aws/aws-lambda-java-libs/tree/master/aws-lambda-java-events) – Input types for events from services that invoke Lambda functions\. -+ [com\.amazonaws:aws\-lambda\-java\-log4j2](https://github.com/aws/aws-lambda-java-libs/tree/master/aws-lambda-java-log4j2) – An appender library for Log4j 2 that you can use to add the request ID for the current invocation to your [function logs](java-logging.md)\. - -These libraries are available through [Maven central repository](https://search.maven.org/search?q=g:com.amazonaws)\. Add them to your build definition as follows\. - ------- -#### [ Gradle ] - -``` -dependencies { - implementation 'com.amazonaws:aws-lambda-java-core:1.2.0' - implementation 'com.amazonaws:aws-lambda-java-events:2.2.7' - runtimeOnly 'com.amazonaws:aws-lambda-java-log4j2:1.1.0' -} -``` - ------- -#### [ Maven ] - -``` - - - com.amazonaws - aws-lambda-java-core - 1.2.0 - - - com.amazonaws - aws-lambda-java-events - 2.2.7 - - - com.amazonaws - aws-lambda-java-log4j2 - 1.1.0 - - -``` - ------- - -To create a deployment package, compile your function code and dependencies into a single ZIP or Java Archive \(JAR\) file\. For Gradle, [use the Zip build type](#java-package-gradle)\. For Maven, [use the Maven Shade plugin](#java-package-maven)\. - -**Note** -To keep your deployment package size small, package your function's dependencies in layers\. Layers let you manage your dependencies independently, can be used by multiple functions, and can be shared with other accounts\. For details, see [AWS Lambda layers](configuration-layers.md)\. - -You can upload your deployment package by using the Lambda console, the Lambda API, or AWS SAM\. - -**To upload a deployment package with the Lambda console** - -1. Open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions)\. - -1. Choose a function\. - -1. Under **Function code**, choose **Upload**\. - -1. Upload the deployment package\. - -1. Choose **Save**\. - -**Topics** -+ [Building a deployment package with Gradle](#java-package-gradle) -+ [Building a deployment package with Maven](#java-package-maven) -+ [Uploading a deployment package with the Lambda API](#java-package-cli) -+ [Uploading a deployment package with AWS SAM](#java-package-cloudformation) - -## Building a deployment package with Gradle - -Use the `Zip` build type to create a deployment package with your function's code and dependencies\. - -**Example build\.gradle – Build task** - -``` -task buildZip(type: Zip) { - from compileJava - from processResources - into('lib') { - from configurations.runtimeClasspath - } -} -``` - -This build configuration produces a deployment package in the `build/distributions` folder\. The `compileJava` task compiles your function's classes\. The `processResources` tasks copies libraries from the build's classpath into a folder named `lib`\. - -**Example build\.gradle – Dependencies** - -``` -dependencies { - implementation platform('software.amazon.awssdk:bom:2.10.73') - implementation 'software.amazon.awssdk:lambda' - implementation 'com.amazonaws:aws-lambda-java-core:1.2.0' - implementation 'com.amazonaws:aws-lambda-java-events:2.2.7' - implementation 'com.google.code.gson:gson:2.8.6' - implementation 'org.apache.logging.log4j:log4j-api:2.13.0' - implementation 'org.apache.logging.log4j:log4j-core:2.13.0' - runtimeOnly 'org.apache.logging.log4j:log4j-slf4j18-impl:2.13.0' - runtimeOnly 'com.amazonaws:aws-lambda-java-log4j2:1.1.0' - testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0' - testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.6.0' -} -``` - -Lambda loads JAR files in Unicode alphabetical order\. If multiple JAR files in the `lib` folder contain the same class, the first one is used\. You can use the following shell script to identify duplicate classes\. - -**Example test\-zip\.sh** - -``` -mkdir -p expanded -unzip path/to/my/function.zip -d expanded -find ./expanded/lib -name '*.jar' | xargs -n1 zipinfo -1 | grep '.*.class' | sort | uniq -c | sort -``` - -## Building a deployment package with Maven - -To build a deployment package with Maven, use the [Maven Shade plugin](https://maven.apache.org/plugins/maven-shade-plugin/)\. The plugin creates a JAR file that contains the compiled function code and all of its dependencies\. - -**Example pom\.xml – Plugin configuration** - -``` - - org.apache.maven.plugins - maven-shade-plugin - 3.2.2 - - false - - - - package - - shade - - - - -``` - -To build the deployment package, use the `mvn package` command\. - -``` -[INFO] Scanning for projects... -[INFO] -----------------------< com.example:java-maven >----------------------- -[INFO] Building java-maven-function 1.0-SNAPSHOT -[INFO] --------------------------------[ jar ]--------------------------------- -... -[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ java-maven --- -[INFO] Building jar: target/java-maven-1.0-SNAPSHOT.jar -[INFO] -[INFO] --- maven-shade-plugin:3.2.2:shade (default) @ java-maven --- -[INFO] Including com.amazonaws:aws-lambda-java-core:jar:1.2.0 in the shaded jar. -[INFO] Including com.amazonaws:aws-lambda-java-events:jar:2.2.7 in the shaded jar. -[INFO] Including joda-time:joda-time:jar:2.6 in the shaded jar. -[INFO] Including com.google.code.gson:gson:jar:2.8.6 in the shaded jar. -[INFO] Replacing original artifact with shaded artifact. -[INFO] Replacing target/java-maven-1.0-SNAPSHOT.jar with target/java-maven-1.0-SNAPSHOT-shaded.jar -[INFO] ------------------------------------------------------------------------ -[INFO] BUILD SUCCESS -[INFO] ------------------------------------------------------------------------ -[INFO] Total time: 8.321 s -[INFO] Finished at: 2020-03-03T09:07:19Z -[INFO] ------------------------------------------------------------------------ -``` - -This command generates a JAR file in the `target` folder\. - -If you use the appender library \(`aws-lambda-java-log4j2`\), you must also configure a transformer for the Maven Shade plugin\. The transformer library combines versions of a cache file that appear in both the appender library and in Log4j\. - -**Example pom\.xml – Plugin configuration with Log4j 2 appender** - -``` - - org.apache.maven.plugins - maven-shade-plugin - 3.2.2 - - false - - - - package - - shade - - - - - - - - - - - - com.github.edwgiz - maven-shade-plugin.log4j2-cachefile-transformer - 2.13.0 - - - -``` - -## Uploading a deployment package with the Lambda API - -To update a function's code with the AWS CLI or AWS SDK, use the [UpdateFunctionCode](API_UpdateFunctionCode.md) API operation\. For the AWS CLI, use the `update-function-code` command\. The following command uploads a deployment package named `my-function.zip` in the current directory\. - -``` -~/my-function$ aws lambda update-function-code --function-name my-function --zip-file fileb://my-function.zip -{ - "FunctionName": "my-function", - "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function", - "Runtime": "java8", - "Role": "arn:aws:iam::123456789012:role/lambda-role", - "Handler": "example.Handler", - "CodeSha256": "Qf0hMc1I2di6YFMi9aXm3JtGTmcDbjniEuiYonYptAk=", - "Version": "$LATEST", - "TracingConfig": { - "Mode": "Active" - }, - "RevisionId": "983ed1e3-ca8e-434b-8dc1-7d72ebadd83d", - ... -} -``` - -If your deployment package is larger than 50 MB, you can't upload it directly\. Upload it to an Amazon S3 bucket and point Lambda to the object\. The following example commands upload a deployment package to a bucket named `my-bucket` and use it to update a function's code\. - -``` -~/my-function$ aws s3 cp my-function.zip s3://my-bucket - upload: my-function.zip to s3://my-bucket/my-function - ~/my-function$ aws lambda update-function-code --function-name my-function \ - --s3-bucket my-bucket --s3-key my-function.zip -{ - "FunctionName": "my-function", - "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function", - "Runtime": "java8", - "Role": "arn:aws:iam::123456789012:role/lambda-role", - "Handler": "example.Handler", - "CodeSha256": "Qf0hMc1I2di6YFMi9aXm3JtGTmcDbjniEuiYonYptAk=", - "Version": "$LATEST", - "TracingConfig": { - "Mode": "Active" - }, - "RevisionId": "983ed1e3-ca8e-434b-8dc1-7d72ebadd83d", - ... -} -``` - -You can use this method to upload function packages up to 250 MB \(decompressed\)\. - -## Uploading a deployment package with AWS SAM - -You can use the AWS Serverless Application Model to automate deployments of your function code, configuration, and dependencies\. AWS SAM is an extension of AWS CloudFormation that provides a simplified syntax for defining serverless applications\. The following example template defines a function with a deployment package in the `build/distributions` directory that Gradle uses\. - -**Example template\.yml** - -``` -AWSTemplateFormatVersion: '2010-09-09' -Transform: 'AWS::Serverless-2016-10-31' -Description: An AWS Lambda application that calls the Lambda API. -Resources: - function: - Type: AWS::Serverless::Function - Properties: - CodeUri: build/distributions/java-basic.zip - Handler: example.Handler - Runtime: java8 - Description: Java function - MemorySize: 512 - Timeout: 10 - # Function's execution role - Policies: - - AWSLambdaBasicExecutionRole - - AWSLambdaReadOnlyAccess - - AWSXrayWriteOnlyAccess - - AWSLambdaVPCAccessExecutionRole - Tracing: Active -``` - -To create the function, use the `package` and `deploy` commands\. These commands are customizations to the AWS CLI\. They wrap other commands to upload the deployment package to Amazon S3, rewrite the template with the object URI, and update the function's code\. - -The following example script runs a Gradle build and uploads the deployment package that it creates\. It creates an AWS CloudFormation stack the first time you run it\. If the stack already exists, the script updates it\. - -**Example deploy\.sh** - -``` -#!/bin/bash -set -eo pipefail -aws cloudformation package --template-file template.yml --s3-bucket MY_BUCKET --output-template-file out.yml -aws cloudformation deploy --template-file out.yml --stack-name java-basic --capabilities CAPABILITY_NAMED_IAM -``` - -For a complete working example, see the following sample applications\. - -**Sample Lambda applications in Java** -+ [blank\-java](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/blank-java) – A Java function that shows the use of Lambda's Java libraries, logging, environment variables, layers, AWS X\-Ray tracing, unit tests, and the AWS SDK\. -+ [java\-basic](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/java-basic) – A minimal Java function with unit tests and variable logging configuration\. -+ [java\-events](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/java-events) – A minimal Java function that uses the [aws\-lambda\-java\-events](#java-package) library with event types that don't require the AWS SDK as a dependency, such as Amazon API Gateway\. -+ [java\-events\-v1sdk](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/java-events-v1sdk) – A Java function that uses the [aws\-lambda\-java\-events](#java-package) library with event types that require the AWS SDK as a dependency \(Amazon Simple Storage Service, Amazon DynamoDB, and Amazon Kinesis\)\. -+ [s3\-java](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/s3-java) – A Java function that processes notification events from Amazon S3 and uses the Java Class Library \(JCL\) to create thumbnails from uploaded image files\. \ No newline at end of file diff --git a/doc_source/java-samples.md b/doc_source/java-samples.md deleted file mode 100644 index 8c7b1290..00000000 --- a/doc_source/java-samples.md +++ /dev/null @@ -1,64 +0,0 @@ -# Java sample applications for AWS Lambda - -The GitHub repository for this guide provides sample applications that demonstrate the use of Java in AWS Lambda\. Each sample application includes scripts for easy deployment and cleanup, an AWS CloudFormation template, and supporting resources\. - -**Sample Lambda applications in Java** -+ [blank\-java](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/blank-java) – A Java function that shows the use of Lambda's Java libraries, logging, environment variables, layers, AWS X\-Ray tracing, unit tests, and the AWS SDK\. -+ [java\-basic](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/java-basic) – A minimal Java function with unit tests and variable logging configuration\. -+ [java\-events](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/java-events) – A minimal Java function that uses the [aws\-lambda\-java\-events](java-package.md) library with event types that don't require the AWS SDK as a dependency, such as Amazon API Gateway\. -+ [java\-events\-v1sdk](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/java-events-v1sdk) – A Java function that uses the [aws\-lambda\-java\-events](java-package.md) library with event types that require the AWS SDK as a dependency \(Amazon Simple Storage Service, Amazon DynamoDB, and Amazon Kinesis\)\. -+ [s3\-java](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/s3-java) – A Java function that processes notification events from Amazon S3 and uses the Java Class Library \(JCL\) to create thumbnails from uploaded image files\. - -Use the `blank-java` sample app to learn the basics, or as a starting point for your own application\. It shows the use of Lambda's Java libraries, environment variables, the AWS SDK, and the AWS X\-Ray SDK\. It uses a Lambda layer to package its dependencies separately from the function code, which speeds up deployment times when you are iterating on your function code\. The project requires minimal setup and can be deployed from the command line in less than a minute\. - -[https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/blank-java](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/blank-java) - -The other sample applications show other build configurations, handler interfaces, and use cases for services that integrate with Lambda\. The `java-basic` sample shows a function with minimal dependencies, for cases where you don't need additional libraries like the AWS SDK and can represent your function's input and output with standard Java types\. To try a different handler type, you can simply change the handler setting on the function\. - -**Example [java\-basic/src/main/java/example/HandlerStream\.java](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/java-basic/src/main/java/example/HandlerStream.java) – Stream handler** - -``` -// Handler value: example.HandlerStream -public class HandlerStream implements RequestStreamHandler { - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - @Override - public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException - { - LambdaLogger logger = context.getLogger(); - BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("US-ASCII"))); - PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream, Charset.forName("US-ASCII")))); - try - { - HashMap event = gson.fromJson(reader, HashMap.class); - logger.log("STREAM TYPE: " + inputStream.getClass().toString()); - logger.log("EVENT TYPE: " + event.getClass().toString()); - writer.write(gson.toJson(event)); - ... -``` - -The `java-events` and `java-events-v1sdk` samples show the use of the event types provided by the `aws-lambda-java-events` library\. These types represent the event documents that [AWS services](lambda-services.md) send to your function\. `java-events` includes handlers for types that don't require additional dependencies\. For event types like `DynamodbEvent` that require types from the AWS SDK for Java, `java-events-v1sdk` includes the SDK in its build configuration\. - -**Example [java\-events\-v1sdk/src/main/java/example/HandlerDynamoDB\.java](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/java-events-v1sdk/src/main/java/example/HandlerDynamoDB.java) – DynamoDB records** - -``` -import com.amazonaws.services.lambda.runtime.events.DynamodbEvent; -import com.amazonaws.services.lambda.runtime.events.DynamodbEvent.DynamodbStreamRecord; -import com.amazonaws.services.dynamodbv2.model.Record; -... -// Handler value: example.HandlerDynamoDB -public class HandlerDynamoDB implements RequestHandler{ - private static final Logger logger = LoggerFactory.getLogger(HandlerDynamoDB.class); - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - @Override - public String handleRequest(DynamodbEvent event, Context context) - { - String response = new String("200 OK"); - for (DynamodbStreamRecord record : event.getRecords()){ - logger.info(record.getEventID()); - logger.info(record.getEventName()); - logger.info(record.getDynamodb().toString()); - } - ... -``` - -For more highlights, see the other topics in this chapter\. \ No newline at end of file diff --git a/doc_source/java-tracing.md b/doc_source/java-tracing.md deleted file mode 100644 index 98860832..00000000 --- a/doc_source/java-tracing.md +++ /dev/null @@ -1,137 +0,0 @@ -# Instrumenting Java code in AWS Lambda - -Lambda integrates with AWS X\-Ray to enable you to trace, debug, and optimize Lambda applications\. You can use X\-Ray to trace a request as it traverses resources in your application, from the frontend API to storage and database on the backend\. By simply adding the X\-Ray SDK library to your build configuration, you can record errors and latency for any call that your function makes to an AWS service\. - -The X\-Ray *service map* shows the flow of requests through your application\. The following example from the [error processor](samples-errorprocessor.md) sample application shows an application with two functions\. The primary function processes events and sometimes returns errors\. The second function processes errors that appear in the first's log group and uses the AWS SDK to call X\-Ray, Amazon S3 and Amazon CloudWatch Logs\. - -[images/sample-errorprocessor-servicemap-l.png](images/sample-errorprocessor-servicemap-l.png) - -You can enable tracing in your function's configuration\. - -**To enable active tracing** - -1. Open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions)\. - -1. Choose a function\. - -1. Under **AWS X\-Ray**, choose **Active tracing**\. - -1. Choose **Save**\. - -Your function needs permission to upload trace data to X\-Ray\. When you enable active tracing in the Lambda console, Lambda adds the required permissions to your function's [execution role](lambda-intro-execution-role.md)\. Otherwise, add the [AWSXRayDaemonWriteAccess](https://console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/AWSXRayDaemonWriteAccess) policy to the execution role\. - -X\-Ray applies a sampling algorithm to ensure that tracing is efficient, while still providing a representative sample of the requests that your application serves\. The default sampling rule is 1 request per second and 5 percent of additional requests\. - -When active tracing is enabled, Lambda records a trace for a subset of invocations\. Lambda records two *segments*, which creates two nodes on the service map\. The first node represents the Lambda service that receives the invocation request\. The second node is recorded by the function's [runtime](gettingstarted-concepts.md#gettingstarted-concepts-runtimes)\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/xray-servicemap-function.png) - -To record detail about calls that your function makes to other resources and services, add the X\-Ray SDK for Java to your build configuration\. The following example shows a Gradle build configuration that includes the libraries that enable automatic instrumentation of AWS SDK for Java 2\.x clients\. - -**Example [build\.gradle](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/blank-java/build.gradle) – Tracing dependencies** - -``` -dependencies { - implementation platform('software.amazon.awssdk:bom:2.10.73') - implementation platform('com.amazonaws:aws-xray-recorder-sdk-bom:2.4.0') - implementation 'software.amazon.awssdk:lambda' - implementation 'com.amazonaws:aws-xray-recorder-sdk-core' - implementation 'com.amazonaws:aws-xray-recorder-sdk-aws-sdk-core' - implementation 'com.amazonaws:aws-xray-recorder-sdk-aws-sdk-v2' - implementation 'com.amazonaws:aws-xray-recorder-sdk-aws-sdk-v2-instrumentor' - ... -} -``` - -You can also instrument HTTP clients, record SQL queries, and create custom subsegments with annotations and metadata\. For more information, see [AWS X\-Ray SDK for Java ](https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-java.html) in the AWS X\-Ray Developer Guide\. - -## Enabling active tracing with the Lambda API - -To manage tracing configuration with the AWS CLI or AWS SDK, use the following API operations: -+ [UpdateFunctionConfiguration](API_UpdateFunctionConfiguration.md) -+ [GetFunctionConfiguration](API_GetFunctionConfiguration.md) -+ [CreateFunction](API_CreateFunction.md) - -The following example AWS CLI command enables active tracing on a function named my\-function\. - -``` -$ aws lambda update-function-configuration --function-name my-function \ ---tracing-config Mode=Active -``` - -Tracing mode is part of the version\-specific configuration that is locked when you publish a version of your function\. You can't change the tracing mode on a published version\. - -## Enabling active tracing with AWS CloudFormation - -To enable active tracing on an `AWS::Lambda::Function` resource in an AWS CloudFormation template, use the `TracingConfig` property\. - -**Example [function\-inline\.yml](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/templates/function-inline.yml) – Tracing configuration** - -``` -Resources: - function: - Type: AWS::Lambda::Function - Properties: - TracingConfig: - Mode: Active - ... -``` - -For an AWS Serverless Application Model \(AWS SAM\) `AWS::Serverless::Function` resource, use the `Tracing` property\. - -**Example [template\.yml](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/blank-java/template.yml) – Tracing configuration** - -``` -Resources: - function: - Type: AWS::Serverless::Function - Properties: - CodeUri: build/distributions/blank-java.zip - Tracing: Active - ... -``` - -If you use the X\-Ray SDK to instrument AWS SDK clients your function code, your deployment package can become quite large\. To avoid uploading runtime dependencies every time you update your functions code, package them in a [Lambda layer](configuration-layers.md)\. The following example shows an `AWS::Serverless::LayerVersion` resource that stores the SDK for Java and X\-Ray SDK for Java\. - -**Example [template\.yml](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/blank-java/template.yml) – Dependencies layer** - -``` -Resources: - function: - Type: AWS::Serverless::Function - Properties: - CodeUri: build/distributions/blank-java.zip - Tracing: Active - Layers: - - !Ref libs - ... - libs: - Type: AWS::Serverless::LayerVersion - Properties: - LayerName: blank-java-lib - Description: Dependencies for the blank-java sample app. - ContentUri: build/blank-java-lib.zip - CompatibleRuntimes: - - java8 -``` - -With this configuration, you only update library JARs if you change your build dependencies\. When you update your function code, you only need to upload your function's compiled classes, so upload times can be much faster\. - -Creating a layer for dependencies requires build configuration changes to generate the layer archive prior to deployment\. For a working example, see the [java\-basic](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/java-basic) sample application\. - -## Tracing in sample applications - -The GitHub repository for this guide includes sample applications that demonstrate the use of tracing\. Each sample application includes scripts for easy deployment and cleanup, an AWS SAM template, and supporting resources\. - -**Sample Lambda applications in Java** -+ [blank\-java](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/blank-java) – A Java function that shows the use of Lambda's Java libraries, logging, environment variables, layers, AWS X\-Ray tracing, unit tests, and the AWS SDK\. -+ [java\-basic](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/java-basic) – A minimal Java function with unit tests and variable logging configuration\. -+ [java\-events](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/java-events) – A minimal Java function that uses the [aws\-lambda\-java\-events](java-package.md) library with event types that don't require the AWS SDK as a dependency, such as Amazon API Gateway\. -+ [java\-events\-v1sdk](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/java-events-v1sdk) – A Java function that uses the [aws\-lambda\-java\-events](java-package.md) library with event types that require the AWS SDK as a dependency \(Amazon Simple Storage Service, Amazon DynamoDB, and Amazon Kinesis\)\. -+ [s3\-java](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/s3-java) – A Java function that processes notification events from Amazon S3 and uses the Java Class Library \(JCL\) to create thumbnails from uploaded image files\. - -All of the sample applications have active tracing enabled for Lambda functions\. The `blank-java` application shows automatic instrumentation of AWS SDK for Java 2\.x clients, segment management for tests, custom subsegments, and the use of Lambda layers to store runtime dependencies\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/blank-java-servicemap.png) - -This example from the `blank-java` sample application shows nodes for the Lambda service, a function, and the Lambda API\. The function calls the Lambda API to monitor storage use in Lambda\. \ No newline at end of file diff --git a/doc_source/kinesis-tutorial-spec.md b/doc_source/kinesis-tutorial-spec.md deleted file mode 100644 index 517aa765..00000000 --- a/doc_source/kinesis-tutorial-spec.md +++ /dev/null @@ -1,43 +0,0 @@ -# AWS SAM template for a DynamoDB application - -You can build this application using [AWS SAM](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/)\. To learn more about creating AWS SAM templates, see [ AWS SAM template basics](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-template-basics.html) in the *AWS Serverless Application Model Developer Guide*\. - -Below is a sample AWS SAM template for the [tutorial application](with-ddb-example.md)\. Copy the text below to a \.yaml file and save it next to the ZIP package you created previously\. Note that the `Handler` and `Runtime` parameter values should match the ones you used when you created the function in the previous section\. - -**Example template\.yaml** - -``` -AWSTemplateFormatVersion: '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Resources: - ProcessDynamoDBStream: - Type: AWS::Serverless::Function - Properties: - Handler: handler - Runtime: runtime - Policies: AWSLambdaDynamoDBExecutionRole - Events: - Stream: - Type: DynamoDB - Properties: - Stream: !GetAtt DynamoDBTable.StreamArn - BatchSize: 100 - StartingPosition: TRIM_HORIZON - - DynamoDBTable: - Type: AWS::DynamoDB::Table - Properties: - AttributeDefinitions: - - AttributeName: id - AttributeType: S - KeySchema: - - AttributeName: id - KeyType: HASH - ProvisionedThroughput: - ReadCapacityUnits: 5 - WriteCapacityUnits: 5 - StreamSpecification: - StreamViewType: NEW_IMAGE -``` - -For information on how to package and deploy your serverless application using the package and deploy commands, see [Deploying serverless applications](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-deploying.html) in the *AWS Serverless Application Model Developer Guide*\. \ No newline at end of file diff --git a/doc_source/lambda-api-permissions-ref.md b/doc_source/lambda-api-permissions-ref.md deleted file mode 100644 index ee316881..00000000 --- a/doc_source/lambda-api-permissions-ref.md +++ /dev/null @@ -1,117 +0,0 @@ -# Resources and conditions for Lambda actions - -You can restrict the scope of a user's permissions by specifying resources and conditions in an IAM policy\. Each API action supports a combination of resource and condition types that varies depending on the behavior of the action\. - -Every IAM policy statement grants permission to an action that's performed on a resource\. When the action doesn't act on a named resource, or when you grant permission to perform the action on all resources, the value of the resource in the policy is a wildcard \(`*`\)\. For many API actions, you can restrict the resources that a user can modify by specifying the Amazon Resource Name \(ARN\) of a resource, or an ARN pattern that matches multiple resources\. - -To restrict permissions by resource, specify the resource by ARN\. - -**Lambda resource ARN format** -+ Function – `arn:aws:lambda:us-west-2:123456789012:function:my-function` -+ Function version – `arn:aws:lambda:us-west-2:123456789012:function:my-function:1` -+ Function alias – `arn:aws:lambda:us-west-2:123456789012:function:my-function:TEST` -+ Event source mapping – `arn:aws:lambda:us-west-2:123456789012:event-source-mapping:fa123456-14a1-4fd2-9fec-83de64ad683de6d47` -+ Layer – `arn:aws:lambda:us-west-2:123456789012:layer:my-layer` -+ Layer version – `arn:aws:lambda:us-west-2:123456789012:layer:my-layer:1` - -For example, the following policy allows a user in account `123456789012` to invoke a function named `my-function` in the US West \(Oregon\) Region\. - -**Example Invoke a function policy** - -``` -{ - "Version": "2012-10-17", - "Statement": [ - { - "Sid": "Invoke", - "Effect": "Allow", - "Action": [ - "lambda:InvokeFunction" - ], - "Resource": "arn:aws:lambda:us-west-2:123456789012:function:my-function" - } - ] -} -``` - -This is a special case where the action identifier \(`lambda:InvokeFunction`\) differs from the API operation \([Invoke](API_Invoke.md)\)\. For other actions, the action identifier is the operation name prefixed by `lambda:`\. - -Conditions are an optional policy element that applies additional logic to determine if an action is allowed\. In addition to [common conditions](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html) supported by all actions, Lambda defines condition types that you can use to restrict the values of additional parameters on some actions\. - -For example, the `lambda:Principal` condition lets you restrict the service or account that a user can grant invocation access to on a function's resource\-based policy\. The following policy lets a user grant permission to SNS topics to invoke a function named `test`\. - -**Example Manage function policy permissions** - -``` -{ - "Version": "2012-10-17", - "Statement": [ - { - "Sid": "ManageFunctionPolicy", - "Effect": "Allow", - "Action": [ - "lambda:AddPermission", - "lambda:RemovePermission" - ], - "Resource": "arn:aws:lambda:us-west-2:123456789012:function:test:*", - "Condition": { - "StringEquals": { - "lambda:Principal": "sns.amazonaws.com" - } - } - } - ] -} -``` - -The condition requires that the principal is Amazon SNS and not another service or account\. The resource pattern requires that the function name is `test` and includes a version number or alias\. For example, `test:v1`\. - -For more information on resources and conditions for Lambda and other AWS services, see [Actions, resources, and condition keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_actions-resources-contextkeys.html) in the *IAM User Guide*\. - -**Topics** -+ [Functions](#permissions-resources-function) -+ [Event source mappings](#permissions-resources-eventsource) -+ [Layers](#permissions-resources-layers) - -## Functions - -Actions that operate on a function can be restricted to a specific function by function, version, or alias ARN, as described in the following table\. Actions that don't support resource restrictions can only be granted for all resources \(`*`\)\. - - -**Functions** - -| Action | Resource | Condition | -| --- | --- | --- | -| [AddPermission](API_AddPermission.md) [RemovePermission](API_RemovePermission.md) | Function Function version Function alias | `lambda:Principal` | -| [Invoke](API_Invoke.md) **Permission:** `lambda:InvokeFunction` | Function Function version Function alias | None | -| [CreateFunction](API_CreateFunction.md) [UpdateFunctionConfiguration](API_UpdateFunctionConfiguration.md) | Function | `lambda:Layer` | -| [CreateAlias](API_CreateAlias.md) [DeleteAlias](API_DeleteAlias.md) [DeleteFunction](API_DeleteFunction.md) [DeleteFunctionConcurrency](API_DeleteFunctionConcurrency.md) [GetAlias](API_GetAlias.md) [GetFunction](API_GetFunction.md) [GetFunctionConfiguration](API_GetFunctionConfiguration.md) [GetPolicy](API_GetPolicy.md) [ListAliases](API_ListAliases.md) [ListVersionsByFunction](API_ListVersionsByFunction.md) [PublishVersion](API_PublishVersion.md) [PutFunctionConcurrency](API_PutFunctionConcurrency.md) [UpdateAlias](API_UpdateAlias.md) [UpdateFunctionCode](API_UpdateFunctionCode.md) | Function | None | -| [GetAccountSettings](API_GetAccountSettings.md) [ListFunctions](API_ListFunctions.md) [ListTags](API_ListTags.md) [TagResource](API_TagResource.md) [UntagResource](API_UntagResource.md) | `*` | None | - -## Event source mappings - -For event source mappings, delete and update permissions can be restricted to a specific event source\. The `lambda:FunctionArn` condition lets you restrict which functions a user can configure an event source to invoke\. - -For these actions, the resource is the event source mapping, so Lambda provides a condition that lets you restrict permission based on the function that the event source mapping invokes\. - - -**Event source mappings** - -| Action | Resource | Condition | -| --- | --- | --- | -| [DeleteEventSourceMapping](API_DeleteEventSourceMapping.md) [UpdateEventSourceMapping](API_UpdateEventSourceMapping.md) | Event source mapping | `lambda:FunctionArn` | -| [CreateEventSourceMapping](API_CreateEventSourceMapping.md) | `*` | `lambda:FunctionArn` | -| [GetEventSourceMapping](API_GetEventSourceMapping.md) [ListEventSourceMappings](API_ListEventSourceMappings.md) | `*` | None | - -## Layers - -Layer actions let you restrict the layers that a user can manage or use with a function\. Actions related to layer use and permissions act on a version of a layer, while `PublishLayerVersion` acts on a layer name\. You can use either with wildcards to restrict the layers that a user can work with by name\. - - -**Layers** - -| Action | Resource | Condition | -| --- | --- | --- | -| [AddLayerVersionPermission](API_AddLayerVersionPermission.md) [RemoveLayerVersionPermission](API_RemoveLayerVersionPermission.md) [GetLayerVersion](API_GetLayerVersion.md) [GetLayerVersionPolicy](API_GetLayerVersionPolicy.md) [DeleteLayerVersion](API_DeleteLayerVersion.md) | Layer version | None | -| [PublishLayerVersion](API_PublishLayerVersion.md) | Layer | None | -| [ListLayers](API_ListLayers.md) [ListLayerVersions](API_ListLayerVersions.md) | `*` | None | \ No newline at end of file diff --git a/doc_source/lambda-csharp.md b/doc_source/lambda-csharp.md deleted file mode 100644 index 84262b02..00000000 --- a/doc_source/lambda-csharp.md +++ /dev/null @@ -1,39 +0,0 @@ -# Building Lambda functions with C\# - -The following sections explain how common programming patterns and core concepts apply when authoring Lambda function code in C\#\. - -AWS Lambda provides the following libraries for C\# functions: -+ **Amazon\.Lambda\.Core** – This library provides a static Lambda logger, serialization interfaces and a context object\. The `Context` object \([AWS Lambda context object in C\#](csharp-context.md)\) provides runtime information about your Lambda function\. -+ **Amazon\.Lambda\.Serialization\.Json ** – This is an implementation of the serialization interface in **Amazon\.Lambda\.Core**\. -+ **Amazon\.Lambda\.Logging\.AspNetCore ** – This provides a library for logging from ASP\.NET\. -+ Event objects \(POCOs\) for several AWS services, including: - + **Amazon\.Lambda\.APIGatewayEvents ** - + **Amazon\.Lambda\.CognitoEvents ** - + **Amazon\.Lambda\.ConfigEvents ** - + **Amazon\.Lambda\.DynamoDBEvents ** - + **Amazon\.Lambda\.KinesisEvents ** - + **Amazon\.Lambda\.S3Events ** - + **Amazon\.Lambda\.SQSEvents ** - + **Amazon\.Lambda\.SNSEvents ** - -These packages are available at [Nuget packages](https://www.nuget.org/packages/)\. - - -**\.NET runtimes** - -| Name | Identifier | Operating system | -| --- | --- | --- | -| \.NET Core 3\.1 | `dotnetcore3.1` | Amazon Linux 2 | -| \.NET Core 2\.1 | `dotnetcore2.1` | Amazon Linux | - -**Note** -To get started with application development in your local environment, deploy one of the sample applications available in this guide's GitHub repository\. -[blank\-csharp](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/blank-csharp) – A C\# function that shows the use of Lambda's \.NET libraries, logging, environment variables, AWS X\-Ray tracing, unit tests, and the AWS SDK\. -[ec2\-spot](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/ec2-spot) – A function that manages spot instance requests in Amazon EC2\. - -**Topics** -+ [AWS Lambda Deployment Package in C\#](csharp-package.md) -+ [AWS Lambda function handler in C\#](csharp-handler.md) -+ [AWS Lambda context object in C\#](csharp-context.md) -+ [AWS Lambda function logging in C\#](csharp-logging.md) -+ [AWS Lambda function errors in C\#](csharp-exceptions.md) \ No newline at end of file diff --git a/doc_source/lambda-edge.md b/doc_source/lambda-edge.md deleted file mode 100644 index 8709e1f3..00000000 --- a/doc_source/lambda-edge.md +++ /dev/null @@ -1,58 +0,0 @@ -# Using AWS Lambda with CloudFront Lambda@Edge - -Lambda@Edge lets you run Node\.js and Python Lambda functions to customize content that CloudFront delivers, executing the functions in AWS locations closer to the viewer\. The functions run in response to CloudFront events, without provisioning or managing servers\. You can use Lambda functions to change CloudFront requests and responses at the following points: -+ After CloudFront receives a request from a viewer \(viewer request\) -+ Before CloudFront forwards the request to the origin \(origin request\) -+ After CloudFront receives the response from the origin \(origin response\) -+ Before CloudFront forwards the response to the viewer \(viewer response\) - -![\[Conceptual graphic that shows how the CloudFront events that can trigger a Lambda function.\]](http://docs.aws.amazon.com/lambda/latest/dg/images/cloudfront-events-that-trigger-lambda-functions.png) - -**Note** -Lambda@Edge supports a limited set of runtimes and features\. For details, see [Requirements and restrictions on Lambda functions](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-requirements-limits.html) in the Amazon CloudFront developer guide\. - -You can also generate responses to viewers without ever sending the request to the origin\. - -**Example CloudFront message event** - -``` -{ - "Records": [ - { - "cf": { - "config": { - "distributionId": "EDFDVBD6EXAMPLE" - }, - "request": { - "clientIp": "2001:0db8:85a3:0:0:8a2e:0370:7334", - "method": "GET", - "uri": "/picture.jpg", - "headers": { - "host": [ - { - "key": "Host", - "value": "d111111abcdef8.cloudfront.net" - } - ], - "user-agent": [ - { - "key": "User-Agent", - "value": "curl/7.51.0" - } - ] - } - } - } - } - ] -} -``` - -With Lambda@Edge, you can build a variety of solutions, for example: -+ Inspect cookies to rewrite URLs to different versions of a site for A/B testing\. -+ Send different objects to your users based on the `User-Agent` header, which contains information about the device that submitted the request\. For example, you can send images in different resolutions to users based on their devices\. -+ Inspect headers or authorized tokens, inserting a corresponding header and allowing access control before forwarding a request to the origin\. -+ Add, delete, and modify headers, and rewrite the URL path to direct users to different objects in the cache\. -+ Generate new HTTP responses to do things like redirect unauthenticated users to login pages, or create and deliver static webpages right from the edge\. For more information, see [Using Lambda functions to generate HTTP responses to viewer and origin requests](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/http-response-generation.html) in the *Amazon CloudFront Developer Guide*\. - -For more information about using Lambda@Edge, see [Using CloudFront with Lambda@Edge](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-at-the-edge.html)\. \ No newline at end of file diff --git a/doc_source/lambda-functions.md b/doc_source/lambda-functions.md deleted file mode 100644 index f77054dd..00000000 --- a/doc_source/lambda-functions.md +++ /dev/null @@ -1,22 +0,0 @@ -# Managing AWS Lambda functions - -You can use the AWS Lambda API or console to configure settings on your Lambda functions\. [Basic function settings](configuration-console.md) include the description, role, and runtime that you specify when you create a function in the Lambda console\. You can configure more settings after you create a function, or use the API to set things like the handler name, memory allocation, and security groups during creation\. - -To keep secrets out of your function code, store them in the function's configuration and read them from the execution environment during initialization\. [Environment variables](configuration-envvars.md) are always encrypted at rest, and can be encrypted client\-side as well\. Use environment variables to make your function code portable by removing connection strings, passwords, and endpoints for external resources\. - -[Versions and aliases](configuration-versions.md) are secondary resources that you can create to manage function deployment and invocation\. Publish [versions](configuration-versions.md) of your function to store its code and configuration as a separate resource that cannot be changed, and create an [alias](configuration-aliases.md) that points to a specific version\. Then you can configure your clients to invoke a function alias, and update the alias when you want to point the client to a new version, instead of updating the client\. - -As you add libraries and other dependencies to your function, creating and uploading a deployment package can slow down development\. Use [layers](configuration-layers.md) to manage your function's dependencies independently and keep your deployment package small\. You can also use layers to share your own libraries with other customers and use publicly available layers with your functions\. - -To use your Lambda function with AWS resources in an Amazon VPC, configure it with security groups and subnets to [create a VPC connection](configuration-vpc.md)\. Connecting your function to a VPC lets you access resources in a private subnet such as relational databases and caches\. You can also [create a database proxy](configuration-database.md) for MySQL and Aurora DB instances\. A database proxy enables a function to reach high concurrency levels without exhausting database connections\. - -**Topics** -+ [Configuring functions in the AWS Lambda console](configuration-console.md) -+ [Using AWS Lambda environment variables](configuration-envvars.md) -+ [Managing concurrency for a Lambda function](configuration-concurrency.md) -+ [AWS Lambda function versions](configuration-versions.md) -+ [AWS Lambda function aliases](configuration-aliases.md) -+ [AWS Lambda layers](configuration-layers.md) -+ [Configuring a Lambda function to access resources in a VPC](configuration-vpc.md) -+ [Configuring database access for a Lambda function](configuration-database.md) -+ [Tagging Lambda Functions](configuration-tags.md) \ No newline at end of file diff --git a/doc_source/lambda-golang.md b/doc_source/lambda-golang.md deleted file mode 100644 index 8894eb0b..00000000 --- a/doc_source/lambda-golang.md +++ /dev/null @@ -1,28 +0,0 @@ -# Building Lambda functions with Go - -The following sections explain how common programming patterns and core concepts apply when authoring Lambda function code in [Go](https://golang.org/)\. - - -**Go runtimes** - -| Name | Identifier | Operating system | -| --- | --- | --- | -| Go 1\.x | `go1.x` | Amazon Linux | - -AWS Lambda provides the following libraries for Go: -+ **github\.com/aws/aws\-lambda\-go/lambda**: The implementation of the Lambda programming model for Go\. This package is used by AWS Lambda to invoke your [handler](golang-handler.md)\. -+ **github\.com/aws/aws\-lambda\-go/lambdacontext**: Helpers for accessing execution context information from the [context object](golang-context.md)\. -+ **github\.com/aws/aws\-lambda\-go/events**: This library provides type definitions for common event source integrations\. - -**Note** -To get started with application development in your local environment, deploy one of the sample applications available in this guide's GitHub repository\. -[blank\-go](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/blank-go) – A Go function that shows the use of Lambda's Go libraries, logging, environment variables, and the AWS SDK\. - -**Topics** -+ [AWS Lambda deployment package in Go](golang-package.md) -+ [AWS Lambda function handler in Go](golang-handler.md) -+ [AWS Lambda context object in Go](golang-context.md) -+ [AWS Lambda function logging in Go](golang-logging.md) -+ [AWS Lambda function errors in Go](golang-exceptions.md) -+ [Instrumenting Go code in AWS Lambda](golang-tracing.md) -+ [Using environment variables](golang-envvars.md) \ No newline at end of file diff --git a/doc_source/lambda-intro-execution-role.md b/doc_source/lambda-intro-execution-role.md deleted file mode 100644 index e2c21758..00000000 --- a/doc_source/lambda-intro-execution-role.md +++ /dev/null @@ -1,127 +0,0 @@ -# AWS Lambda execution role - -An AWS Lambda function's execution role grants it permission to access AWS services and resources\. You provide this role when you create a function, and Lambda assumes the role when your function is invoked\. You can create an execution role for development that has permission to send logs to Amazon CloudWatch and upload trace data to AWS X\-Ray\. - -**To view a function's execution role** - -1. Open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions)\. - -1. Choose a function\. - -1. Choose **Permissions**\. - -1. The resource summary shows the services and resources that the function has access to\. The following example shows the CloudWatch Logs permissions that Lambda adds to an execution role when you create it in the Lambda console\. -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/permissions-executionrole.png) - -1. Choose a service from the drop\-down menu to see permissions related to that service\. - -You can add or remove permissions from a function's execution role at any time, or configure your function to use a different role\. Add permissions for any services that your function calls with the AWS SDK, and for services that Lambda uses to enable optional features\. - -When you add permissions to your function, make an update to its code or configuration as well\. This forces running instances of your function, which have out\-of\-date credentials, to stop and be replaced\. - -## Creating an execution role in the IAM console - -By default, Lambda creates an execution role with minimal permissions when you [create a function](getting-started-create-function.md) in the Lambda console\. You can also create an execution role in the IAM console\. - -**To create an execution role in the IAM console** - -1. Open the [roles page](https://console.aws.amazon.com/iam/home#/roles) in the IAM console\. - -1. Choose **Create role**\. - -1. Under **Common use cases**, choose **Lambda**\. - -1. Choose **Next: Permissions**\. - -1. Under **Attach permissions policies**, choose the **AWSLambdaBasicExecutionRole** and **AWSXRayDaemonWriteAccess** managed policies\. - -1. Choose **Next: Tags**\. - -1. Choose **Next: Review**\. - -1. For **Role name**, enter **lambda\-role**\. - -1. Choose **Create role**\. - -For detailed instructions, see [Creating a role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html#roles-creatingrole-service-console) in the IAM User Guide\. - -## Managing roles with the IAM API - -An execution role is an IAM role that Lambda has permission to assume when you invoke a function\. To create an execution role with the AWS CLI, use the `create-role` command\. - -``` -$ aws iam create-role --role-name lambda-ex --assume-role-policy-document file://trust-policy.json -{ - "Role": { - "Path": "/", - "RoleName": "lambda-ex", - "RoleId": "AROAQFOXMPL6TZ6ITKWND", - "Arn": "arn:aws:iam::123456789012:role/lambda-ex", - "CreateDate": "2020-01-17T23:19:12Z", - "AssumeRolePolicyDocument": { - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Allow", - "Principal": { - "Service": "lambda.amazonaws.com" - }, - "Action": "sts:AssumeRole" - } - ] - } - } -} -``` - -The `trust-policy.json` file is a JSON file in the current directory that defines the [trust policy](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html) for the role\. This trust policy allows Lambda to use the role's permissions by giving the service principal `lambda.amazonaws.com` permission to call the AWS Security Token Service `AssumeRole` action\. - -**Example trust\-policy\.json** - -``` -{ - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Allow", - "Principal": { - "Service": "lambda.amazonaws.com" - }, - "Action": "sts:AssumeRole" - } - ] -} -``` - -You can also specify the trust policy inline\. Requirements for escaping quotes in the JSON string vary depending on your shell\. - -``` -$ aws iam create-role --role-name lambda-ex --assume-role-policy-document '{"Version": "2012-10-17","Statement": [{ "Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"}, "Action": "sts:AssumeRole"}]}' -``` - -To add permissions to the role, use the `attach-policy-to-role` command\. Start by adding the `AWSLambdaBasicExecutionRole` managed policy\. - -``` -$ aws iam attach-role-policy --role-name lambda-ex --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole -``` - -## Managed policies for Lambda features - -The following managed policies provide permissions that are required to use Lambda features: -+ **AWSLambdaBasicExecutionRole** – Permission to upload logs to CloudWatch\. -+ **AWSLambdaKinesisExecutionRole** – Permission to read events from an Amazon Kinesis data stream or consumer\. -+ **AWSLambdaDynamoDBExecutionRole** – Permission to read records from an Amazon DynamoDB stream\. -+ **AWSLambdaSQSQueueExecutionRole** – Permission to read a message from an Amazon Simple Queue Service \(Amazon SQS\) queue\. -+ **AWSLambdaVPCAccessExecutionRole** – Permission to manage elastic network interfaces to connect your function to a VPC\. -+ **AWSXRayDaemonWriteAccess** – Permission to upload trace data to X\-Ray\. - -For some features, the Lambda console attempts to add missing permissions to your execution role in a customer managed policy\. These policies can become numerous\. Add the relevant managed policies to your execution role before enabling features to avoid creating extra policies\. - -When you use an [event source mapping](invocation-eventsourcemapping.md) to invoke your function, Lambda uses the execution role to read event data\. For example, an event source mapping for Amazon Kinesis reads events from a data stream and sends them to your function in batches\. You can use event source mappings with the following services: - -**Services that Lambda reads events from** -+ [Amazon Kinesis](with-kinesis.md) -+ [Amazon DynamoDB](with-ddb.md) -+ [Amazon Simple Queue Service](with-sqs.md) - -In addition to the managed policies, the Lambda console provides templates for creating a custom policy that has the permissions related to additional use cases\. When you create a function in the Lambda console, you can choose to create a new execution role with permissions from one or more templates\. These templates are also applied automatically when you create a function from a blueprint, or when you configure options that require access to other services\. Example templates are available in this guide's [GitHub repository](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/iam-policies)\. \ No newline at end of file diff --git a/doc_source/lambda-invocation.md b/doc_source/lambda-invocation.md deleted file mode 100644 index c268c968..00000000 --- a/doc_source/lambda-invocation.md +++ /dev/null @@ -1,22 +0,0 @@ -# Invoking AWS Lambda functions - -You can invoke Lambda functions directly [with the Lambda console](getting-started-create-function.md#get-started-invoke-manually), the Lambda API, the AWS SDK, the AWS CLI, and AWS toolkits\. You can also configure other AWS services to invoke your function, or you can configure Lambda to read from a stream or queue and invoke your function\. - -When you invoke a function, you can choose to invoke it synchronously or asynchronously\. With [synchronous invocation](invocation-sync.md), you wait for the function to process the event and return a response\. With [asynchronous](invocation-async.md) invocation, Lambda queues the event for processing and returns a response immediately\. For asynchronous invocation, Lambda handles retries and can send invocation records to a [destination](invocation-async.md#invocation-async-destinations)\. - -To use your function to process data automatically, add one or more triggers\. A trigger is a Lambda resource or a resource in another service that you configure to invoke your function in response to lifecycle events, external requests, or on a schedule\. Your function can have multiple triggers\. Each trigger acts as an client invoking your function independently\. Each event that Lambda passes to your function only has data from one client or trigger\. - -To process items from a stream or queue, you can create an [event source mapping](invocation-eventsourcemapping.md)\. An event source mapping is a resource in Lambda that reads items from an Amazon SQS queue, an Amazon Kinesis stream, or an Amazon DynamoDB stream, and sends them to your function in batches\. Each event that your function processes can contain hundreds or thousands of items\. - -Other AWS services and resources invoke your function directly\. For example, you can configure CloudWatch Events to invoke your function on a timer, or you can configure Amazon S3 to invoke your function when an object is created\. Each service varies in the method it uses to invoke your function, the structure of the event, and how you configure it\. For more information, see [Using AWS Lambda with other services](lambda-services.md)\. - -Depending on who invokes your function and how it's invoked, scaling behavior and the types of errors that occur can vary\. When you invoke a function synchronously, you receive errors in the response and can retry\. When you invoke asynchronously, use an event source mapping, or configure another service to invoke your function, the retry requirements and the way that your function scales to handle large numbers of events can vary\. For details, see [AWS Lambda function scaling](invocation-scaling.md) and [Error handling and automatic retries in AWS Lambda](invocation-retries.md)\. - -**Topics** -+ [Synchronous invocation](invocation-sync.md) -+ [Asynchronous invocation](invocation-async.md) -+ [AWS Lambda event source mappings](invocation-eventsourcemapping.md) -+ [Monitoring the state of a function with the Lambda API](functions-states.md) -+ [AWS Lambda function scaling](invocation-scaling.md) -+ [Error handling and automatic retries in AWS Lambda](invocation-retries.md) -+ [Invoking Lambda functions with the AWS Mobile SDK for Android](with-on-demand-custom-android.md) \ No newline at end of file diff --git a/doc_source/lambda-java.md b/doc_source/lambda-java.md deleted file mode 100644 index f75d8dae..00000000 --- a/doc_source/lambda-java.md +++ /dev/null @@ -1,75 +0,0 @@ -# Building Lambda functions with Java - -You can run Java code in AWS Lambda\. Lambda provides [runtimes](lambda-runtimes.md) for Java that execute your code to process events\. Your code runs in an Amazon Linux environment that includes AWS credentials from an AWS Identity and Access Management \(IAM\) role that you manage\. - -Lambda supports the following Java runtimes\. - - -**Java runtimes** - -| Name | Identifier | JDK | Operating system | -| --- | --- | --- | --- | -| Java 11 | `java11` | amazon\-corretto\-11 | Amazon Linux 2 | -| Java 8 | `java8` | java\-1\.8\.0\-openjdk | Amazon Linux | - -Lambda functions use an [execution role](lambda-intro-execution-role.md) to get permission to write logs to Amazon CloudWatch Logs, and to access other services and resources\. If you don't already have an execution role for function development, create one\. - -**To create an execution role** - -1. Open the [roles page](https://console.aws.amazon.com/iam/home#/roles) in the IAM console\. - -1. Choose **Create role**\. - -1. Create a role with the following properties\. - + **Trusted entity** – **Lambda**\. - + **Permissions** – **AWSLambdaBasicExecutionRole**\. - + **Role name** – **lambda\-role**\. - - The **AWSLambdaBasicExecutionRole** policy has the permissions that the function needs to write logs to CloudWatch Logs\. - -You can add permissions to the role later, or swap it out for a different role that's specific to a single function\. - -**To create a Java function** - -1. Open the [Lambda console](https://console.aws.amazon.com/lambda)\. - -1. Choose **Create function**\. - -1. Configure the following settings: - + **Name** – **my\-function**\. - + **Runtime** – **Java 11**\. - + **Role** – **Choose an existing role**\. - + **Existing role** – **lambda\-role**\. - -1. Choose **Create function**\. - -1. To configure a test event, choose **Test**\. - -1. For **Event name**, enter **test**\. - -1. Choose **Create**\. - -1. To execute the function, choose **Test**\. - -The console creates a Lambda function with a handler class named `Hello`\. Since Java is a compiled language, you can't view or edit the source code in the Lambda console, but you can modify its configuration, invoke it, and configure triggers\. - -**Note** -To get started with application development in your local environment, deploy one of the [sample applications](java-samples.md) available in this guide's GitHub repository\. - -The `Hello` class has a function named `handleRequest` that takes an event object and a context object\. This is the [handler function](java-handler.md) that Lambda calls when the function is invoked\. The Java function runtime gets invocation events from Lambda and passes them to the handler\. In the function configuration, the handler value is `example.Hello::handleRequest`\. - -To update the function's code, you create a deployment package, which is a ZIP archive that contains your function code\. As your function development progresses, you will want to store your function code in source control, add libraries, and automate deployments\. Start by [creating a deployment package](java-package.md) and updating your code at the command line\. - -The function runtime passes a context object to the handler, in addition to the invocation event\. The [context object](java-context.md) contains additional information about the invocation, the function, and the execution environment\. More information is available from environment variables\. - -Your Lambda function comes with a CloudWatch Logs log group\. The function runtime sends details about each invocation to CloudWatch Logs\. It relays any [logs that your function outputs](java-logging.md) during invocation\. If your function [returns an error](java-exceptions.md), Lambda formats the error and returns it to the invoker\. - -**Topics** -+ [Java sample applications for AWS Lambda](java-samples.md) -+ [AWS Lambda deployment package in Java](java-package.md) -+ [AWS Lambda function handler in Java](java-handler.md) -+ [AWS Lambda context object in Java](java-context.md) -+ [AWS Lambda function logging in Java](java-logging.md) -+ [AWS Lambda function errors in Java](java-exceptions.md) -+ [Instrumenting Java code in AWS Lambda](java-tracing.md) -+ [Creating a deployment package using Eclipse](java-package-eclipse.md) \ No newline at end of file diff --git a/doc_source/lambda-monitoring.md b/doc_source/lambda-monitoring.md deleted file mode 100644 index 93eab1b9..00000000 --- a/doc_source/lambda-monitoring.md +++ /dev/null @@ -1,19 +0,0 @@ -# Monitoring and troubleshooting Lambda applications - -AWS Lambda automatically monitors Lambda functions on your behalf and reports metrics through Amazon CloudWatch\. To help you monitor your code as it executes, Lambda automatically tracks the number of requests, the execution duration per request, and the number of requests that result in an error\. It also publishes the associated CloudWatch metrics\. You can leverage these metrics to set CloudWatch custom alarms\. For more information about CloudWatch, see the *[Amazon CloudWatch User Guide](https://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/)*\. - -You can view request rates and error rates for each of your Lambda functions by using the AWS Lambda console, the CloudWatch console, and other AWS resources\. The following topics describe Lambda CloudWatch metrics and how to access them\. -+ [Monitoring functions in the AWS Lambda console](monitoring-functions-access-metrics.md) -+ [Working with AWS Lambda function metrics](monitoring-metrics.md) - -You can insert logging statements into your code to help you validate that your code is working as expected\. Lambda automatically integrates with Amazon CloudWatch Logs\. It pushes all logs from your code to a CloudWatch Logs group that is associated with a Lambda function \(/aws/lambda/**\)\. To learn more about log groups and accessing them through the CloudWatch console, see [Working with log groups and log streams](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Working-with-log-groups-and-streams.html) in the *Amazon CloudWatch Logs User Guide*\. For information about how to access CloudWatch log entries, see [Accessing Amazon CloudWatch logs for AWS Lambda](monitoring-cloudwatchlogs.md)\. - -**Note** -If your Lambda function code is executing, but you don't see any log data being generated after several minutes, this could mean that your execution role for the Lambda function didn't grant permissions to write log data to CloudWatch Logs\. For information about how to make sure that you have set up the execution role correctly to grant these permissions, see [AWS Lambda execution role](lambda-intro-execution-role.md)\. - -Each of the monitoring services provides a free tier\. If your application exceeds the free tier limits, pricing is based on usage\. For more information, see [ CloudWatch pricing](https://aws.amazon.com/cloudwatch/pricing/) and [X\-Ray pricing](https://aws.amazon.com/xray/pricing/)\. Also note that standard storage rates apply for CloudWatch logs that are stored by the Lambda service\. - -The monitoring services follow these usage models: -+ AWS Lambda reports metrics and logs to CloudWatch every time your Lambda function executes\. -+ CloudWatch Logs Insights runs when you view the Monitoring page of your Lambda function\. -+ X\-Ray starts to record traces when you enable X\-Ray for a function, or when an upstream service enables X\-Ray\. \ No newline at end of file diff --git a/doc_source/lambda-nodejs.md b/doc_source/lambda-nodejs.md deleted file mode 100644 index f1449830..00000000 --- a/doc_source/lambda-nodejs.md +++ /dev/null @@ -1,81 +0,0 @@ -# Building Lambda functions with Node\.js - -You can run JavaScript code with Node\.js in AWS Lambda\. Lambda provides [runtimes](lambda-runtimes.md) for Node\.js that execute your code to process events\. Your code runs in an environment that includes the AWS SDK for JavaScript, with credentials from an AWS Identity and Access Management \(IAM\) role that you manage\. - -Lambda supports the following Node\.js runtimes\. - - -**Node\.js runtimes** - -| Name | Identifier | AWS SDK for JavaScript | Operating system | -| --- | --- | --- | --- | -| Node\.js 12 | `nodejs12.x` | 2\.631\.0 | Amazon Linux 2 | -| Node\.js 10 | `nodejs10.x` | 2\.631\.0 | Amazon Linux 2 | - -Lambda functions use an [execution role](lambda-intro-execution-role.md) to get permission to write logs to Amazon CloudWatch Logs, and to access other services and resources\. If you don't already have an execution role for function development, create one\. - -**To create an execution role** - -1. Open the [roles page](https://console.aws.amazon.com/iam/home#/roles) in the IAM console\. - -1. Choose **Create role**\. - -1. Create a role with the following properties\. - + **Trusted entity** – **Lambda**\. - + **Permissions** – **AWSLambdaBasicExecutionRole**\. - + **Role name** – **lambda\-role**\. - - The **AWSLambdaBasicExecutionRole** policy has the permissions that the function needs to write logs to CloudWatch Logs\. - -You can add permissions to the role later, or swap it out for a different role that's specific to a single function\. - -**To create a Node\.js function** - -1. Open the [Lambda console](https://console.aws.amazon.com/lambda)\. - -1. Choose **Create function**\. - -1. Configure the following settings: - + **Name** – **my\-function**\. - + **Runtime** – **Node\.js 12\.x**\. - + **Role** – **Choose an existing role**\. - + **Existing role** – **lambda\-role**\. - -1. Choose **Create function**\. - -1. To configure a test event, choose **Test**\. - -1. For **Event name**, enter **test**\. - -1. Choose **Create**\. - -1. To execute the function, choose **Test**\. - -The console creates a Lambda function with a single source file named `index.js`\. You can edit this file and add more files in the built\-in [code editor](code-editor.md)\. To save your changes, choose **Save**\. Then, to run your code, choose **Test**\. - -**Note** -The Lambda console uses AWS Cloud9 to provide an integrated development environment in the browser\. You can also use AWS Cloud9 to develop Lambda functions in your own environment\. For more information, see [Working with AWS Lambda Functions](https://docs.aws.amazon.com/cloud9/latest/user-guide/lambda-functions.html) in the AWS Cloud9 user guide\. - -The `index.js` file exports a function named `handler` that takes an event object and a context object\. This is the [handler function](nodejs-handler.md) that Lambda calls when the function is invoked\. The Node\.js function runtime gets invocation events from Lambda and passes them to the handler\. In the function configuration, the handler value is `index.handler`\. - -Each time you save your function code, the Lambda console creates a deployment package, which is a ZIP archive that contains your function code\. As your function development progresses, you will want to store your function code in source control, add libraries, and automate deployments\. Start by [creating a deployment package](nodejs-package.md) and updating your code at the command line\. - -**Note** -To get started with application development in your local environment, deploy one of the sample applications available in this guide's GitHub repository\. -[blank\-nodejs](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/blank-nodejs) – A Node\.js function that shows the use of logging, environment variables, AWS X\-Ray tracing, layers, unit tests and the AWS SDK\. -[nodejs\-apig](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/nodejs-apig) – A function with a public API endpoint that processes an event from API Gateway and returns an HTTP response\. -[rds\-mysql](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/rds-mysql) – A function that relays queries to a MySQL for RDS Database\. This sample includes a private VPC and database instance configured with a password in AWS Secrets Manager\. -[list\-manager](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/list-manager) – A function processes events from an Amazon Kinesis data stream and update aggregate lists in Amazon DynamoDB\. The function stores a record of each event in a MySQL for RDS Database in a private VPC\. This sample includes a private VPC with a VPC endpoint for DynamoDB and a database instance\. -[error\-processor](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/error-processor) – A Node\.js function generates errors for a specified percentage of requests\. A CloudWatch Logs subscription invokes a second function when an error is recorded\. The processor function uses the AWS SDK to gather details about the request and stores them in an Amazon S3 bucket\. - -The function runtime passes a context object to the handler, in addition to the invocation event\. The [context object](nodejs-context.md) contains additional information about the invocation, the function, and the execution environment\. More information is available from environment variables\. - -Your Lambda function comes with a CloudWatch Logs log group\. The function runtime sends details about each invocation to CloudWatch Logs\. It relays any [logs that your function outputs](nodejs-logging.md) during invocation\. If your function [returns an error](nodejs-exceptions.md), Lambda formats the error and returns it to the invoker\. - -**Topics** -+ [AWS Lambda function handler in Node\.js](nodejs-handler.md) -+ [AWS Lambda deployment package in Node\.js](nodejs-package.md) -+ [AWS Lambda context object in Node\.js](nodejs-context.md) -+ [AWS Lambda function logging in Node\.js](nodejs-logging.md) -+ [AWS Lambda function errors in Node\.js](nodejs-exceptions.md) -+ [Instrumenting Node\.js code in AWS Lambda](nodejs-tracing.md) \ No newline at end of file diff --git a/doc_source/lambda-permissions.md b/doc_source/lambda-permissions.md deleted file mode 100644 index 6574b109..00000000 --- a/doc_source/lambda-permissions.md +++ /dev/null @@ -1,23 +0,0 @@ -# AWS Lambda permissions - -You can use AWS Identity and Access Management \(IAM\) to manage access to the Lambda API and resources like functions and layers\. For users and applications in your account that use Lambda, you manage permissions in a permissions policy that you can apply to IAM users, groups, or roles\. To grant permissions to other accounts or AWS services that use your Lambda resources, you use a policy that applies to the resource itself\. - -A Lambda function also has a policy, called an [execution role](lambda-intro-execution-role.md), that grants it permission to access AWS services and resources\. At a minimum, your function needs access to Amazon CloudWatch Logs for log streaming\. If you [use AWS X\-Ray to trace your function](lambda-x-ray.md), or your function accesses services with the AWS SDK, you grant it permission to call them in the execution role\. Lambda also uses the execution role to get permission to read from event sources when you use an [event source mapping](invocation-eventsourcemapping.md) to trigger your function\. - -**Note** -If your function needs network access to a resource like a relational database that isn't accessible through AWS APIs or the internet, [configure it to connect to your VPC](configuration-vpc.md)\. - -Use [resource\-based policies](access-control-resource-based.md) to give other accounts and AWS services permission to use your Lambda resources\. Lambda resources include functions, versions, aliases, and layer versions\. Each of these resources has a permissions policy that applies when the resource is accessed, in addition to any policies that apply to the user\. When an AWS service like Amazon S3 calls your Lambda function, the resource\-based policy gives it access\. - -To manage permissions for users and applications in your accounts, [use the managed policies that Lambda provides](access-control-identity-based.md), or write your own\. The Lambda console uses multiple services to get information about your function's configuration and triggers\. You can use the managed policies as\-is, or as a starting point for more restrictive policies\. - -You can restrict user permissions by the resource an action affects and, in some cases, by additional conditions\. For example, you can specify a pattern for the Amazon Resource Name \(ARN\) of a function that requires a user to include their user name in the name of functions that they create\. Additionally, you can add a condition that requires that the user configure functions to use a specific layer to, for example, pull in logging software\. For the resources and conditions that are supported by each action, see [Resources and Conditions](lambda-api-permissions-ref.md)\. - -For more information about IAM, see [What is IAM?](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) in the *IAM User Guide*\. - -**Topics** -+ [AWS Lambda execution role](lambda-intro-execution-role.md) -+ [Using resource\-based policies for AWS Lambda](access-control-resource-based.md) -+ [Identity\-based IAM policies for AWS Lambda](access-control-identity-based.md) -+ [Resources and conditions for Lambda actions](lambda-api-permissions-ref.md) -+ [Using permissions boundaries for AWS Lambda applications](permissions-boundary.md) \ No newline at end of file diff --git a/doc_source/lambda-powershell.md b/doc_source/lambda-powershell.md deleted file mode 100644 index 8016c0d3..00000000 --- a/doc_source/lambda-powershell.md +++ /dev/null @@ -1,27 +0,0 @@ -# Building Lambda functions with PowerShell - -The following sections explain how common programming patterns and core concepts apply when you author Lambda function code in PowerShell\. - - -**\.NET runtimes** - -| Name | Identifier | Operating system | -| --- | --- | --- | -| \.NET Core 3\.1 | `dotnetcore3.1` | Amazon Linux 2 | -| \.NET Core 2\.1 | `dotnetcore2.1` | Amazon Linux | - -**Note** -To get started with application development in your local environment, deploy one of the sample applications available in this guide's GitHub repository\. -[blank\-powershell](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/blank-powershell) – A PowerShell function that shows the use of logging, environment variables, and the AWS SDK\. - -Before you get started, you must first set up a PowerShell development environment\. For instructions on how to do this, see [Setting Up a PowerShell Development Environment](powershell-devenv.md)\. - -To learn about how to use the AWSLambdaPSCore module to download sample PowerShell projects from templates, create PowerShell deployment packages, and deploy PowerShell functions to the AWS Cloud, see [AWS Lambda deployment package in PowerShell](powershell-package.md)\. - -**Topics** -+ [Setting Up a PowerShell Development Environment](powershell-devenv.md) -+ [AWS Lambda deployment package in PowerShell](powershell-package.md) -+ [AWS Lambda function handler in PowerShell](powershell-handler.md) -+ [AWS Lambda context object in PowerShell](powershell-context.md) -+ [AWS Lambda function logging in PowerShell](powershell-logging.md) -+ [AWS Lambda function errors in PowerShell](powershell-exceptions.md) \ No newline at end of file diff --git a/doc_source/lambda-python.md b/doc_source/lambda-python.md deleted file mode 100644 index 8e1b9e50..00000000 --- a/doc_source/lambda-python.md +++ /dev/null @@ -1,79 +0,0 @@ -# Building Lambda functions with Python - -You can run Python code in AWS Lambda\. Lambda provides [runtimes](lambda-runtimes.md) for Python that execute your code to process events\. Your code runs in an environment that includes the SDK for Python \(Boto 3\), with credentials from an AWS Identity and Access Management \(IAM\) role that you manage\. - -Lambda supports the following Python runtimes\. - - -**Python runtimes** - -| Name | Identifier | AWS SDK for Python | Operating system | -| --- | --- | --- | --- | -| Python 3\.8 | `python3.8` | boto3\-1\.12\.22 botocore\-1\.15\.22 | Amazon Linux 2 | -| Python 3\.7 | `python3.7` | boto3\-1\.12\.22 botocore\-1\.15\.22 | Amazon Linux | -| Python 3\.6 | `python3.6` | boto3\-1\.12\.22 botocore\-1\.15\.22 | Amazon Linux | -| Python 2\.7 | `python2.7` | boto3\-1\.12\.22 botocore\-1\.15\.22 | Amazon Linux | - -Lambda functions use an [execution role](lambda-intro-execution-role.md) to get permission to write logs to Amazon CloudWatch Logs, and to access other services and resources\. If you don't already have an execution role for function development, create one\. - -**To create an execution role** - -1. Open the [roles page](https://console.aws.amazon.com/iam/home#/roles) in the IAM console\. - -1. Choose **Create role**\. - -1. Create a role with the following properties\. - + **Trusted entity** – **Lambda**\. - + **Permissions** – **AWSLambdaBasicExecutionRole**\. - + **Role name** – **lambda\-role**\. - - The **AWSLambdaBasicExecutionRole** policy has the permissions that the function needs to write logs to CloudWatch Logs\. - -You can add permissions to the role later, or swap it out for a different role that's specific to a single function\. - -**To create a Python function** - -1. Open the [Lambda console](https://console.aws.amazon.com/lambda)\. - -1. Choose **Create function**\. - -1. Configure the following settings: - + **Name** – **my\-function**\. - + **Runtime** – **Python 3\.8**\. - + **Role** – **Choose an existing role**\. - + **Existing role** – **lambda\-role**\. - -1. Choose **Create function**\. - -1. To configure a test event, choose **Test**\. - -1. For **Event name**, enter **test**\. - -1. Choose **Create**\. - -1. To execute the function, choose **Test**\. - -The console creates a Lambda function with a single source file named `lambda_function`\. You can edit this file and add more files in the built\-in [code editor](code-editor.md)\. To save your changes, choose **Save**\. Then, to run your code, choose **Test**\. - -**Note** -The Lambda console uses AWS Cloud9 to provide an integrated development environment in the browser\. You can also use AWS Cloud9 to develop Lambda functions in your own environment\. For more information, see [Working with AWS Lambda Functions](https://docs.aws.amazon.com/cloud9/latest/user-guide/lambda-functions.html) in the AWS Cloud9 user guide\. - -The `lambda_function` file exports a function named `lambda_handler` that takes an event object and a context object\. This is the [handler function](python-handler.md) that Lambda calls when the function is invoked\. The Python function runtime gets invocation events from Lambda and passes them to the handler\. In the function configuration, the handler value is `lambda_function.lambda_handler`\. - -Each time you save your function code, the Lambda console creates a deployment package, which is a ZIP archive that contains your function code\. As your function development progresses, you will want to store your function code in source control, add libraries, and automate deployments\. Start by [creating a deployment package](python-package.md) and updating your code at the command line\. - -**Note** -To get started with application development in your local environment, deploy one of the sample applications available in this guide's GitHub repository\. -[blank\-python](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/blank-python) – A Python function that shows the use of logging, environment variables, AWS X\-Ray tracing, layers, unit tests and the AWS SDK\. - -The function runtime passes a context object to the handler, in addition to the invocation event\. The [context object](python-context.md) contains additional information about the invocation, the function, and the execution environment\. More information is available from environment variables\. - -Your Lambda function comes with a CloudWatch Logs log group\. The function runtime sends details about each invocation to CloudWatch Logs\. It relays any [logs that your function outputs](python-logging.md) during invocation\. If your function [returns an error](python-exceptions.md), Lambda formats the error and returns it to the invoker\. - -**Topics** -+ [AWS Lambda function handler in Python](python-handler.md) -+ [AWS Lambda deployment package in Python](python-package.md) -+ [AWS Lambda context object in Python](python-context.md) -+ [AWS Lambda function logging in Python](python-logging.md) -+ [AWS Lambda function errors in Python](python-exceptions.md) -+ [Instrumenting Python code in AWS Lambda](python-tracing.md) \ No newline at end of file diff --git a/doc_source/lambda-releases.md b/doc_source/lambda-releases.md deleted file mode 100644 index 75fa3db4..00000000 --- a/doc_source/lambda-releases.md +++ /dev/null @@ -1,88 +0,0 @@ -# AWS Lambda releases - -The following table describes the important changes to the *AWS Lambda Developer Guide* since May 2018\. For notification about updates to this documentation, subscribe to the [RSS feed](https://docs.aws.amazon.com/lambda/latest/dg/lambda-updates.rss)\. - -| Change | Description | Date | -| --- |--- |--- | -| [Support for \.NET Core 3\.1\.0 runtime in AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/csharp-package-cli.html?icmpid=docs_lambda_rss) | AWS Lambda now supports the \.NET Core 3\.1\.0 runtime\. For details, see [\.NET Core CLI](https://docs.aws.amazon.com/lambda/latest/dg/csharp-package-cli.html?icmpid=docs_lambda_rss)\. | March 31, 2020 | -| [Support for API Gateway HTTP APIs](https://docs.aws.amazon.com/lambda/latest/dg/services-apigateway.html?icmpid=docs_lambda_rss) | Updated and expanded documentation for using Lambda with API Gateway, including support for HTTP APIs\. Added a sample application that creates an API and function with AWS CloudFormation\. For details, see [Using AWS Lambda with Amazon API Gateway](https://docs.aws.amazon.com/lambda/latest/dg/services-apigateway.html?icmpid=docs_lambda_rss)\. | March 23, 2020 | -| [Ruby 2\.7](https://docs.aws.amazon.com/lambda/latest/dg/lambda-ruby.html?icmpid=docs_lambda_rss) | A new runtime is available for Ruby 2\.7, ruby2\.7, which is the first Ruby runtime to use Amazon Linux 2\. For details, see [Building Lambda functions with Ruby](https://docs.aws.amazon.com/lambda/latest/dg/lambda-ruby.html?icmpid=docs_lambda_rss)\. | February 19, 2020 | -| [Concurrency metrics](https://docs.aws.amazon.com/lambda/latest/dg/monitoring-metrics.html?icmpid=docs_lambda_rss) | AWS Lambda now reports the `ConcurrentExecutions` metric for all functions, aliases, and versions\. You can view a graph for this metric on the monitoring page for your function\. Previously, `ConcurrentExecutions` was only reported at the account level and for functions that use reserved concurrency\. For details, see [AWS Lambda function metrics](https://docs.aws.amazon.com/lambda/latest/dg/monitoring-metrics.html?icmpid=docs_lambda_rss)\. | February 18, 2020 | -| [Update to function states](https://docs.aws.amazon.com/lambda/latest/dg/functions-states.html?icmpid=docs_lambda_rss) | Function states are now enforced for all functions by default\. When you connect a function to a VPC, Lambda creates shared elastic network interfaces\. This enables your function to scale up without creating additional network interfaces\. During this time, you can't perform additional operations on the function, including updating its configuration and publishing versions\. In some cases, invocation is also impacted\. Details about a function's current state are available from the Lambda API\.This update is being released in phases\. For details, see [Updated Lambda states lifecycle for VPC networking](https://aws.amazon.com/blogs/compute/coming-soon-updated-lambda-states-lifecycle-for-vpc-networking/) on the AWS Compute Blog\. For more information about states, see [AWS Lambda function states](https://docs.aws.amazon.com/lambda/latest/dg/functions-states.html?icmpid=docs_lambda_rss)\. | January 24, 2020 | -| [Updates to function configuration API output](https://docs.aws.amazon.com/lambda/latest/dg/API_FunctionConfiguration.html?icmpid=docs_lambda_rss) | Added reason codes to [StateReasonCode](https://docs.aws.amazon.com/lambda/latest/dg/API_GetFunctionConfiguration.html?icmpid=docs_lambda_rss#SSS-GetFunctionConfiguration-response-LastUpdateStatusReasonCode) \(InvalidSubnet, InvalidSecurityGroup\) and LastUpdateStatusReasonCode \(SubnetOutOfIPAddresses, InvalidSubnet, InvalidSecurityGroup\) for functions that connect to a VPC\. For more information about states, see [AWS Lambda function states](https://docs.aws.amazon.com/lambda/latest/dg/functions-states.html?icmpid=docs_lambda_rss)\. | January 20, 2020 | -| [Provisioned concurrency](https://docs.aws.amazon.com/lambda/latest/dg/configuration-concurrency.html?icmpid=docs_lambda_rss) | You can now allocate provisioned concurrency for a function version or alias\. Provisioned concurrency enables a function to scale without fluctuations in latency\. For details, see [Managing concurrency for a Lambda function](https://docs.aws.amazon.com/lambda/latest/dg/configuration-concurrency.html?icmpid=docs_lambda_rss)\. | December 3, 2019 | -| [Create a database proxy](https://docs.aws.amazon.com/lambda/latest/dg/configuration-database.html?icmpid=docs_lambda_rss) | You can now use the Lambda console to create a database proxy for a Lambda function\. A database proxy enables a function to reach high concurrency levels without exhausting database connections\. For details, see [Configuring database access for a Lambda function](https://docs.aws.amazon.com/lambda/latest/dg/configuration-database.html?icmpid=docs_lambda_rss)\. | December 3, 2019 | -| [Percentiles support for the duration metric](https://docs.aws.amazon.com/lambda/latest/dg/monitoring-metrics.html?icmpid=docs_lambda_rss) | You can now filter the duration metric based on percentiles\. For details, see [AWS Lambda metrics](https://docs.aws.amazon.com/lambda/latest/dg/monitoring-metrics.html?icmpid=docs_lambda_rss)\. | November 26, 2019 | -| [Increased concurrency for stream event sources](https://docs.aws.amazon.com/lambda/latest/dg/invocation-eventsourcemapping.html?icmpid=docs_lambda_rss) | A new option for [DynamoDB stream](https://docs.aws.amazon.com/lambda/latest/dg/with-ddb.html?icmpid=docs_lambda_rss) and [Kinesis stream](https://docs.aws.amazon.com/lambda/latest/dg/with-kinesis.html?icmpid=docs_lambda_rss) event source mappings enables you to process more than one batch at a time from each shard\. When you increase the number of concurrent batches per shard, your function's concurrency can be up to 10 times the number of shards in your stream\. For details, see [AWS Lambda event source mapping](https://docs.aws.amazon.com/lambda/latest/dg/invocation-eventsourcemapping.html?icmpid=docs_lambda_rss)\. | November 25, 2019 | -| [Function states](https://docs.aws.amazon.com/lambda/latest/dg/functions-states.html?icmpid=docs_lambda_rss) | When you create or update a function, it enters a pending state while Lambda provisions resources to support it\. If you connect your function to a VPC, Lambda can create a shared elastic network interface right away, instead of creating network interfaces when your function is invoked\. This results in better performance for VPC\-connected functions, but might require an update to your automation\. For details, see [AWS Lambda function states](https://docs.aws.amazon.com/lambda/latest/dg/functions-states.html?icmpid=docs_lambda_rss)\. | November 25, 2019 | -| [Error handling options for asynchronous invocation](https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html?icmpid=docs_lambda_rss#invocation-async-errors) | New configuration options are available for asynchronous invocation\. You can configure Lambda to limit retries and set a maximum event age\. For details, see [Configuring error handling for asynchronous invocation](https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html?icmpid=docs_lambda_rss#invocation-async-errors)\. | November 25, 2019 | -| [Error handling for stream event sources](https://docs.aws.amazon.com/lambda/latest/dg/invocation-eventsourcemapping.html?icmpid=docs_lambda_rss) | New configuration options are available for event source mappings that read from streams\. You can configure [DynamoDB stream](https://docs.aws.amazon.com/lambda/latest/dg/with-ddb.html?icmpid=docs_lambda_rss) and [Kinesis stream](https://docs.aws.amazon.com/lambda/latest/dg/with-kinesis.html?icmpid=docs_lambda_rss) event source mappings to limit retries and set a maximum record age\. When errors occur, you can configure the event source mapping to split batches before retrying, and to send invocation records for failed batches to a queue or topic\. For details, see [AWS Lambda event source mapping](https://docs.aws.amazon.com/lambda/latest/dg/invocation-eventsourcemapping.html?icmpid=docs_lambda_rss)\. | November 25, 2019 | -| [Destinations for asynchronous invocation](https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html?icmpid=docs_lambda_rss#invocation-async-destinations) | You can now configure Lambda to send records of asynchronous invocations to another service\. Invocation records contain details about the event, context, and function response\. You can send invocation records to an SQS queue, SNS topic, Lambda function, or EventBridge event bus\. For details, see [Configuring destinations for asynchronous invocation](https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html?icmpid=docs_lambda_rss#invocation-async-destinations)\. | November 25, 2019 | -| [New runtimes for Node\.js, Python, and Java](https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html?icmpid=docs_lambda_rss) | New runtimes are available for Node\.js 12, Python 3\.8, and Java 11\. For details, see [AWS Lambda runtimes](https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html?icmpid=docs_lambda_rss)\. | November 18, 2019 | -| [FIFO queue support for Amazon SQS event sources](https://docs.aws.amazon.com/lambda/latest/dg/with-sqs.html?icmpid=docs_lambda_rss) | You can now create an event source mapping that reads from a first\-in, first\-out \(FIFO\) queue\. Previously, only standard queues were supported\. For details, see [Using AWS Lambda with Amazon SQS](https://docs.aws.amazon.com/lambda/latest/dg/with-sqs.html?icmpid=docs_lambda_rss)\. | November 18, 2019 | -| [Create applications in the Lambda console](https://docs.aws.amazon.com/lambda/latest/dg/applications-tutorial.html?icmpid=docs_lambda_rss) | Application creation in the Lambda console is now generally available\. For instructions, see [Creating an application with continuous delivery in the Lambda console](https://docs.aws.amazon.com/lambda/latest/dg/applications-tutorial.html?icmpid=docs_lambda_rss)\. | October 31, 2019 | -| [Create applications in the Lambda console \(beta\)](https://docs.aws.amazon.com/lambda/latest/dg/applications-tutorial.html?icmpid=docs_lambda_rss) | You can now create a Lambda application with an integrated continuous delivery pipeline in the Lambda console\. The console provides sample applications that you can use as a starting point for your own project\. Choose between AWS CodeCommit and GitHub for source control\. Each time you push changes to your repository, the included pipeline builds and deploys them automatically\. For instructions, see [Creating an application with continuous delivery in the Lambda console](https://docs.aws.amazon.com/lambda/latest/dg/applications-tutorial.html?icmpid=docs_lambda_rss)\. | October 3, 2019 | -| [Performance improvements for VPC\-connected functions](https://docs.aws.amazon.com/lambda/latest/dg/configuration-vpc.html?icmpid=docs_lambda_rss) | Lambda now uses a new type of elastic network interface that is shared by all functions in a virtual private cloud \(VPC\) subnet\. When you connect a function to a VPC, Lambda creates a network interface for each combination of security group and subnet that you choose\. When the shared network interfaces are available, the function no longer needs to create additional network interfaces as it scales up\. This dramatically improves startup times\. For details, see [Configuring a Lambda function to access resources in a VPC](https://docs.aws.amazon.com/lambda/latest/dg/configuration-vpc.html?icmpid=docs_lambda_rss)\. | September 3, 2019 | -| [Stream batch settings](https://docs.aws.amazon.com/lambda/latest/dg/with-ddb.html?icmpid=docs_lambda_rss) | You can now configure a batch window for [Amazon DynamoDB](https://docs.aws.amazon.com/lambda/latest/dg/with-ddb.html?icmpid=docs_lambda_rss) and [Amazon Kinesis](https://docs.aws.amazon.com/lambda/latest/dg/with-kinesis.html?icmpid=docs_lambda_rss) event source mappings\. Configure a batch window of up to five minutes to buffer incoming records until a full batch is available\. This reduces the number of times that your function is invoked when the stream is less active\. | August 29, 2019 | -| [CloudWatch Logs Insights integration](https://docs.aws.amazon.com/lambda/latest/dg/monitoring-functions-access-metrics.html?icmpid=docs_lambda_rss) | The monitoring page in the Lambda console now includes reports from Amazon CloudWatch Logs Insights\. For details, see [Monitoring functions in the AWS Lambda console](https://docs.aws.amazon.com/lambda/latest/dg/monitoring-functions-access-metrics.html?icmpid=docs_lambda_rss)\. | June 18, 2019 | -| [Amazon Linux 2018\.03](https://docs.aws.amazon.com/lambda/latest/dg/current-supported-versions.html?icmpid=docs_lambda_rss) | The Lambda execution environment is being updated to use Amazon Linux 2018\.03\. For details, see [Execution environment](https://docs.aws.amazon.com/lambda/latest/dg/current-supported-versions.html?icmpid=docs_lambda_rss)\. | May 21, 2019 | -| [Node\.js 10](https://docs.aws.amazon.com/lambda/latest/dg/programming-model.html?icmpid=docs_lambda_rss) | A new runtime is available for Node\.js 10, nodejs10\.x\. This runtime uses Node\.js 10\.15 and will be updated with the latest point release of Node\.js 10 periodically\. Node\.js 10 is also the first runtime to use Amazon Linux 2\. For details, see [Building Lambda functions with Node\.js](https://docs.aws.amazon.com/lambda/latest/dg/programming-model.html?icmpid=docs_lambda_rss)\. | May 13, 2019 | -| [GetLayerVersionByArn API](https://docs.aws.amazon.com/lambda/latest/dg/API_GetLayerVersionByArn.html?icmpid=docs_lambda_rss) | Use the [GetLayerVersionByArn](https://docs.aws.amazon.com/lambda/latest/dg/API_GetLayerVersionByArn.html?icmpid=docs_lambda_rss) API to download layer version information with the version ARN as input\. Compared to GetLayerVersion, GetLayerVersionByArn lets you use the ARN directly instead of parsing it to get the layer name and version number\. | April 25, 2019 | -| [Ruby](https://docs.aws.amazon.com/lambda/latest/dg/lambda-ruby.html?icmpid=docs_lambda_rss) | AWS Lambda now supports Ruby 2\.5 with a new runtime\. For details, see [Building Lambda functions with Ruby](https://docs.aws.amazon.com/lambda/latest/dg/lambda-ruby.html?icmpid=docs_lambda_rss)\. | November 29, 2018 | -| [Layers](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html?icmpid=docs_lambda_rss) | With Lambda layers, you can package and deploy libraries, custom runtimes, and other dependencies separately from your function code\. Share your layers with your other accounts or the whole world\. For details, see [AWS Lambda layers](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html?icmpid=docs_lambda_rss)\. | November 29, 2018 | -| [Custom runtimes](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html?icmpid=docs_lambda_rss) | Build a custom runtime to run Lambda functions in your favorite programming language\. For details, see [Custom AWS Lambda runtimes](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html?icmpid=docs_lambda_rss)\. | November 29, 2018 | -| [Application Load Balancer triggers](https://docs.aws.amazon.com/lambda/latest/dg/services-alb.html?icmpid=docs_lambda_rss) | Elastic Load Balancing now supports Lambda functions as a target for Application Load Balancers\. For details, see [Using Lambda with application load balancers](https://docs.aws.amazon.com/lambda/latest/dg/services-alb.html?icmpid=docs_lambda_rss)\. | November 29, 2018 | -| [Use Kinesis HTTP/2 stream consumers as a trigger](https://docs.aws.amazon.com/lambda/latest/dg/with-kinesis.html?icmpid=docs_lambda_rss) | You can use Kinesis HTTP/2 data stream consumers to send events to AWS Lambda\. Stream consumers have dedicated read throughput from each shard in your data stream and use HTTP/2 to minimize latency\. For details, see [Using AWS Lambda with Kinesis](https://docs.aws.amazon.com/lambda/latest/dg/with-kinesis.html?icmpid=docs_lambda_rss)\. | November 19, 2018 | -| [Python 3\.7](https://docs.aws.amazon.com/lambda/latest/dg/lambda-python.html?icmpid=docs_lambda_rss) | AWS Lambda now supports Python 3\.7 with a new runtime\. For more information, see [Building Lambda functions with Python](https://docs.aws.amazon.com/lambda/latest/dg/lambda-python.html?icmpid=docs_lambda_rss)\. | November 19, 2018 | -| [Payload limit increase for asynchronous function invocation](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-limits.html?icmpid=docs_lambda_rss) | The maximum payload size for asynchronous invocations increased from 128 KB to 256 KB, which matches the maximum message size from an Amazon SNS trigger\. For details, see [AWS Lambda limits](https://docs.aws.amazon.com/lambda/latest/dg/limits.html?icmpid=docs_lambda_rss)\. | November 16, 2018 | -| [AWS GovCloud \(US\-East\) Region](https://docs.aws.amazon.com/lambda/latest/dg/lambda-releases.html?icmpid=docs_lambda_rss) | AWS Lambda is now available in the AWS GovCloud \(US\-East\) Region\. For details, see [AWS GovCloud \(US\-East\) now open](https://aws.amazon.com/blogs/aws/aws-govcloud-us-east-now-open/?icmpid=docs_lambda_rss) on the AWS blog\. | November 12, 2018 | -| [Moved AWS SAM topics to a separate Developer Guide](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/?icmpid=docs_lambda_rss) | A number of topics were focused on building serverless applications using the AWS Serverless Application Model \(AWS SAM\)\. These topics have been moved to [ AWS Serverless Application Model developer guide](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/)\. | October 25, 2018 | -| [View Lambda applications in the console](https://docs.aws.amazon.com/lambda/latest/dg/applications-console.html?icmpid=docs_lambda_rss) | You can view the status of your Lambda applications on the [Applications](https://docs.aws.amazon.com/lambda/latest/dg/applications-console.html?icmpid=docs_lambda_rss) page in the Lambda console\. This page shows the status of the AWS CloudFormation stack\. It includes links to pages where you can view more information about the resources in the stack\. You can also view aggregate metrics for the application and create custom monitoring dashboards\. | October 11, 2018 | -| [Function execution timeout limit](https://docs.aws.amazon.com/lambda/latest/dg/limits.html?icmpid=docs_lambda_rss) | To allow for long\-running functions, the maximum configurable execution timeout increased from 5 minutes to 15 minutes\. For details, see [AWS Lambda limits](https://docs.aws.amazon.com/lambda/latest/dg/limits.html?icmpid=docs_lambda_rss)\. | October 10, 2018 | -| [Support for PowerShell Core language in AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/powershell-programming-model.html?icmpid=docs_lambda_rss) | AWS Lambda now supports the PowerShell Core language\. For more information, see [Programming model for authoring Lambda functions in PowerShell](https://docs.aws.amazon.com/lambda/latest/dg/powershell-programming-model.html?icmpid=docs_lambda_rss)\. | September 11, 2018 | -| [Support for \.NET Core 2\.1\.0 runtime in AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/lambda-dotnet-coreclr-deployment-package.html?icmpid=docs_lambda_rss) | AWS Lambda now supports the \.NET Core 2\.1\.0 runtime\. For more information, see [\.NET Core CLI](https://docs.aws.amazon.com/lambda/latest/dg/lambda-dotnet-coreclr-deployment-package.html?icmpid=docs_lambda_rss)\. | July 9, 2018 | -| [Updates now available over RSS](https://docs.aws.amazon.com/lambda/latest/dg/history.html?icmpid=docs_lambda_rss) | You can now subscribe to an RSS feed to follow releases for this guide\. | July 5, 2018 | -| [Support for Amazon SQS as event source](https://docs.aws.amazon.com/lambda/latest/dg/lambda-invocation.html?icmpid=docs_lambda_rss) | AWS Lambda now supports Amazon Simple Queue Service \(Amazon SQS\) as an event source\. For more information, see [Invoking Lambda functions](https://docs.aws.amazon.com/lambda/latest/dg/lambda-invocation.html?icmpid=docs_lambda_rss)\. | June 28, 2018 | -| [China \(Ningxia\) Region](https://docs.aws.amazon.com/lambda/latest/dg/history.html?icmpid=docs_lambda_rss) | AWS Lambda is now available in the China \(Ningxia\) Region\. For more information about Lambda Regions and endpoints, see [Regions and endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html?icmpid=docs_lambda_rss) in the *AWS General Reference*\. | June 28, 2018 | - -## Earlier updates - -The following table describes the important changes in each release of the *AWS Lambda Developer Guide* before June 2018\. - - -| Change | Description | Date | -| --- | --- | --- | -| Runtime support for Node\.js runtime 8\.10 | AWS Lambda now supports Node\.js runtime version 8\.10\. For more information, see [Building Lambda functions with Node\.js](lambda-nodejs.md)\. | April 2, 2018 | -| Function and alias revision IDs | AWS Lambda now supports revision IDs on your function versions and aliases\. You can use these IDs to track and apply conditional updates when you are updating your function version or alias resources\. | January 25, 2018 | -| Runtime support for Go and \.NET 2\.0 | AWS Lambda has added runtime support for Go and \.NET 2\.0\. For more information, see [Building Lambda functions with Go](lambda-golang.md) and [Building Lambda functions with C\#](lambda-csharp.md)\. | January 15, 2018 | -| Console Redesign | AWS Lambda has introduced a new Lambda console to simplify your experience and added a Cloud9 Code Editor to enhance your ability debug and revise your function code\. For more information, see [Creating functions using the AWS Lambda console editor](code-editor.md)\. | November 30,2017 | -| Setting Concurrency Limits on Individual Functions | AWS Lambda now supports setting concurrency limits on individual functions\. For more information, see [Managing concurrency for a Lambda function](configuration-concurrency.md)\. | November 30,2017 | -| Shifting Traffic with Aliases | AWS Lambda now supports shifting traffic with aliases\. For more information, see [Rolling deployments for Lambda functions ](lambda-rolling-deployments.md)\. | November 28, 2017 | -| Gradual Code Deployment | AWS Lambda now supports safely deploying new versions of your Lambda function by leveraging Code Deploy\. For more information, see [ Gradual code deployment](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/automating-updates-to-serverless-apps.html)\. | November 28, 2017 | -| China \(Beijing\) Region | AWS Lambda is now available in the China \(Beijing\) Region\. For more information about Lambda regions and endpoints, see [Regions and endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html#lambda_region) in the *AWS General Reference*\. | November 9, 2017 | -| Introducing SAM Local | AWS Lambda introduces SAM Local \(now known as SAM CLI\), a AWS CLI tool that provides an environment for you to develop, test, and analyze your serverless applications locally before uploading them to the Lambda runtime\. For more information, see [ Testing and debugging serverless applications](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-test-and-debug.html)\. | August 11, 2017 | -| Canada \(Central\) Region | AWS Lambda is now available in the Canada \(Central\) Region\. For more information about Lambda regions and endpoints, see [Regions and endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html#lambda_region) in the *AWS General Reference*\. | June 22, 2017 | -| South America \(São Paulo\) Region | AWS Lambda is now available in the South America \(São Paulo\) Region\. For more information about Lambda regions and endpoints, see [Regions and endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html#lambda_region) in the *AWS General Reference*\. | June 6, 2017 | -| AWS Lambda support for AWS X\-Ray\. | Lambda introduces support for X\-Ray, which allows you to detect, analyze, and optimize performance issues with your Lambda applications\. For more information, see [Using AWS X\-Ray](lambda-x-ray.md)\. | April 19, 2017 | -| Asia Pacific \(Mumbai\) Region | AWS Lambda is now available in the Asia Pacific \(Mumbai\) Region\. For more information about Lambda regions and endpoints, see [Regions and endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html#lambda_region) in the *AWS General Reference*\. | March 28, 2017 | -| AWS Lambda now supports Node\.js runtime v6\.10 | AWS Lambda added support for Node\.js runtime v6\.10\. For more information, see [Building Lambda functions with Node\.js](lambda-nodejs.md)\. | March 22, 2017 | -| Europe \(London\) Region | AWS Lambda is now available in the Europe \(London\) Region\. For more information about Lambda regions and endpoints, see [Regions and endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html#lambda_region) in the *AWS General Reference*\. | February 1, 2017 | -| AWS Lambda support for the \.NET runtime, Lambda@Edge \(Preview\), Dead Letter Queues and automated deployment of serverless applications\. | AWS Lambda added support for C\#\. For more information, see [Building Lambda functions with C\#](lambda-csharp.md)\. Lambda@Edge allows you to run Lambda functions at the AWS Edge locations in response to CloudFront events\. For more information, see [Using AWS Lambda with CloudFront Lambda@Edge](lambda-edge.md)\. | December 3, 2016 | -| AWS Lambda adds Amazon Lex as a supported event source\. | Using Lambda and Amazon Lex, you can quickly build chat bots for various services like Slack and Facebook\. For more information, see [Using AWS Lambda with Amazon Lex](services-lex.md)\. | November 30, 2016 | -| US West \(N\. California\) Region | AWS Lambda is now available in the US West \(N\. California\) Region\. For more information about Lambda regions and endpoints, see [Regions and endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html#lambda_region) in the *AWS General Reference*\. | November 21, 2016 | -| Introduced the AWS Serverless Application Model for creating and deploying Lambda\-based applications and using environment variables for Lambda function configuration settings\. | AWS Serverless Application Model: You can now use the AWS SAM to define the syntax for expressing resources within a serverless application\. In order to deploy your application, simply specify the resources you need as part of your application, along with their associated permissions policies in a AWS CloudFormation template file \(written in either JSON or YAML\), package your deployment artifacts, and deploy the template\. For more information, see [AWS Lambda applications](deploying-lambda-apps.md)\. Environment variables: You can use environment variables to specify configuration settings for your Lambda function outside of your function code\. For more information, see [Using AWS Lambda environment variables](configuration-envvars.md)\. | November 18, 2016 | -| Asia Pacific \(Seoul\) Region | AWS Lambda is now available in the Asia Pacific \(Seoul\) Region\. For more information about Lambda regions and endpoints, see [Regions and endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html#lambda_region) in the *AWS General Reference*\. | August 29, 2016 | -| Asia Pacific \(Sydney\) Region | Lambda is now available in the Asia Pacific \(Sydney\) Region\. For more information about Lambda regions and endpoints, see [Regions and endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html#lambda_region) in the *AWS General Reference*\. | June 23, 2016 | -| Updates to the Lambda console | The Lambda console has been updated to simplify the role\-creation process\. For more information, see [Create a Lambda function with the console](getting-started-create-function.md)\. | June 23, 2016 | -| AWS Lambda now supports Node\.js runtime v4\.3 | AWS Lambda added support for Node\.js runtime v4\.3\. For more information, see [Building Lambda functions with Node\.js](lambda-nodejs.md)\. | April 07, 2016 | -| Europe \(Frankfurt\) region | Lambda is now available in the Europe \(Frankfurt\) region\. For more information about Lambda regions and endpoints, see [Regions and endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html#lambda_region) in the *AWS General Reference*\. | March 14, 2016 | -| VPC support | You can now configure a Lambda function to access resources in your VPC\. For more information, see [Configuring a Lambda function to access resources in a VPC](configuration-vpc.md)\. | February 11, 2016 | -| AWS Lambda runtime has been updated\. | The [execution environment](lambda-runtimes.md) has been updated\. | November 4, 2015 | -| Versioning support, Python for developing code for Lambda functions, scheduled events, and increase in execution time | You can now develop your Lambda function code using Python\. For more information, see [Building Lambda functions with Python](lambda-python.md)\. Versioning: You can maintain one or more versions of your Lambda function\. Versioning allows you to control which Lambda function version is executed in different environments \(for example, development, testing, or production\)\. For more information, see [AWS Lambda function versions](configuration-versions.md)\. Scheduled events: You can also set up AWS Lambda to invoke your code on a regular, scheduled basis using the AWS Lambda console\. You can specify a fixed rate \(number of hours, days, or weeks\) or you can specify a cron expression\. For an example, see [Using AWS Lambda with Amazon CloudWatch Events](services-cloudwatchevents.md)\. Increase in execution time: You can now set up your Lambda functions to run for up to five minutes allowing longer running functions such as large volume data ingestion and processing jobs\. | October 08, 2015 | -| Support for DynamoDB Streams | DynamoDB Streams is now generally available and you can use it in all the regions where DynamoDB is available\. You can enable DynamoDB Streams for your table and use a Lambda function as a trigger for the table\. Triggers are custom actions you take in response to updates made to the DynamoDB table\. For an example walkthrough, see [Tutorial: Using AWS Lambda with Amazon DynamoDB streams](with-ddb-example.md) \. | July 14, 2015 | -| AWS Lambda now supports invoking Lambda functions with REST\-compatible clients\. | Until now, to invoke your Lambda function from your web, mobile, or IoT application you needed the AWS SDKs \(for example, AWS SDK for Java, AWS SDK for Android, or AWS SDK for iOS\)\. Now, AWS Lambda supports invoking a Lambda function with REST\-compatible clients through a customized API that you can create using Amazon API Gateway\. You can send requests to your Lambda function endpoint URL\. You can configure security on the endpoint to allow open access, leverage AWS Identity and Access Management \(IAM\) to authorize access, or use API keys to meter access to your Lambda functions by others\. For an example Getting Started exercise, see [Using AWS Lambda with Amazon API Gateway](services-apigateway.md)\. For more information about the Amazon API Gateway, see [https://aws\.amazon\.com/api\-gateway/](https://aws.amazon.com/api-gateway/)\. | July 09, 2015 | -| The AWS Lambda console now provides blueprints to easily create Lambda functions and test them\. | AWS Lambda console provides a set of *blueprints*\. Each blueprint provides a sample event source configuration and sample code for your Lambda function that you can use to easily create Lambda\-based applications\. All of the AWS Lambda Getting Started exercises now use the blueprints\. For more information, see [Getting started with AWS Lambda](getting-started.md)\. | July 09, 2015 | -| AWS Lambda now supports Java to author your Lambda functions\. | You can now author Lambda code in Java\. For more information, see [Building Lambda functions with Java](lambda-java.md)\. | June 15, 2015 | -| AWS Lambda now supports specifying an Amazon S3 object as the function \.zip when creating or updating a Lambda function\. | You can upload a Lambda function deployment package \(\.zip file\) to an Amazon S3 bucket in the same region where you want to create a Lambda function\. Then, you can specify the bucket name and object key name when you create or update a Lambda function\. | May 28, 2015 | -| AWS Lambda now generally available with added support for mobile backends | AWS Lambda is now generally available for production use\. The release also introduces new features that make it easier to build mobile, tablet, and Internet of Things \(IoT\) backends using AWS Lambda that scale automatically without provisioning or managing infrastructure\. AWS Lambda now supports both real\-time \(synchronous\) and asynchronous events\. Additional features include easier event source configuration and management\. The permission model and the programming model have been simplified by the introduction of resource policies for your Lambda functions\. The documentation has been updated accordingly\. For information, see the following topics: [Getting started with AWS Lambda](getting-started.md) [AWS Lambda](https://aws.amazon.com/lambda/) | April 9, 2015 | -| Preview release | Preview release of the *AWS Lambda Developer Guide*\. | November 13, 2014 | \ No newline at end of file diff --git a/doc_source/lambda-rolling-deployments.md b/doc_source/lambda-rolling-deployments.md deleted file mode 100644 index 170ea8b6..00000000 --- a/doc_source/lambda-rolling-deployments.md +++ /dev/null @@ -1,51 +0,0 @@ -# Rolling deployments for Lambda functions - -Use rolling deployments to control the risks associated with introducing new versions of your Lambda function\. In a rolling deployment, the system automatically deploys the new version of the function and gradually sends an increasing amount of traffic to the new version\. The amount of traffic and rate of increase are parameters that you can configure\. - -You configure a rolling deployment by using AWS CodeDeploy and AWS SAM\. CodeDeploy is a service that automates application deployments to Amazon computing platforms such as Amazon EC2 and AWS Lambda\. For more information, see [What is CodeDeploy?](https://docs.aws.amazon.com/codedeploy/latest/userguide/welcome.html)\. By using CodeDeploy to deploy your Lambda function, you can easily monitor the status of the deployment and initiate a rollback if you detect any issues\. - -AWS SAM is an open\-source framework for building serverless applications\. You create an AWS SAM template \(in YAML format\) to specify the configuration of the components required for the rolling deployment\. AWS SAM uses the template to create and configure the components\. For more information, see [What is the AWS Serverless Application Model?](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html)\. - -In a rolling deployment, AWS SAM performs these tasks: -+ It configures your Lambda function and creates an alias\. - - The alias routing configuration is the underlying capability that implements the rolling deployment\. -+ It creates a CodeDeploy application and deployment group\. - - The deployment group manages the rolling deployment and the rollback \(if needed\)\. -+ It detects when you create a new version of your Lambda function\. -+ It triggers CodeDeploy to start the deployment of the new version\. - -## Example AWS SAM Lambda template - -The following example shows an [AWS SAM template](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-template-basics.html) for a simple rolling deployment\. - -``` -AWSTemplateFormatVersion : '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Description: A sample SAM template for deploying Lambda functions. - -Resources: -# Details about the myDateTimeFunction Lambda function - myDateTimeFunction: - Type: AWS::Serverless::Function - Properties: - Handler: myDateTimeFunction.handler - Runtime: nodejs12.x -# Creates an alias named "live" for the function, and automatically publishes when you update the function. - AutoPublishAlias: live - DeploymentPreference: -# Specifies the deployment configuration - Type: Linear10PercentEvery2Minutes -``` - -This template defines a Lambda function named `myDateTimeFunction` with the following properties\. - -**AutoPublishAlias ** -The `AutoPublishAlias` property creates an alias named `live`\. In addition, the AWS SAM framework automatically detects when you save new code for the function\. The framework then publishes a new function version and updates the `live` alias to point to the new version\. - -**DeploymentPreference** -The `DeploymentPreference` property determines the rate at which the CodeDeploy application shifts traffic from the original version of the Lambda function to the new version\. The value `Linear10PercentEvery2Minutes` shifts an additional ten percent of the traffic to the new version every two minutes\. -For a list of the predefined deployment configurations, see [Deployment configurations](https://docs.aws.amazon.com/codedeploy/latest/userguide/deployment-configurations.html)\. - -For a detailed tutorial on how to use CodeDeploy with Lambda functions, see [Deploy an updated Lambda function with CodeDeploy](https://docs.aws.amazon.com/codedeploy/latest/userguide/tutorial-lambda-sam.html)\. \ No newline at end of file diff --git a/doc_source/lambda-ruby.md b/doc_source/lambda-ruby.md deleted file mode 100644 index 9193bc3f..00000000 --- a/doc_source/lambda-ruby.md +++ /dev/null @@ -1,76 +0,0 @@ -# Building Lambda functions with Ruby - -You can run Ruby code in AWS Lambda\. Lambda provides [runtimes](lambda-runtimes.md) for Ruby that execute your code to process events\. Your code runs in an environment that includes the AWS SDK for Ruby, with credentials from an AWS Identity and Access Management \(IAM\) role that you manage\. - -Lambda supports the following Ruby runtimes\. - - -**Ruby runtimes** - -| Name | Identifier | AWS SDK for Ruby | Operating system | -| --- | --- | --- | --- | -| Ruby 2\.7 | `ruby2.7` | 3\.0\.1 | Amazon Linux 2 | -| Ruby 2\.5 | `ruby2.5` | 3\.0\.1 | Amazon Linux | - -Lambda functions use an [execution role](lambda-intro-execution-role.md) to get permission to write logs to Amazon CloudWatch Logs, and to access other services and resources\. If you don't already have an execution role for function development, create one\. - -**To create an execution role** - -1. Open the [roles page](https://console.aws.amazon.com/iam/home#/roles) in the IAM console\. - -1. Choose **Create role**\. - -1. Create a role with the following properties\. - + **Trusted entity** – **Lambda**\. - + **Permissions** – **AWSLambdaBasicExecutionRole**\. - + **Role name** – **lambda\-role**\. - - The **AWSLambdaBasicExecutionRole** policy has the permissions that the function needs to write logs to CloudWatch Logs\. - -You can add permissions to the role later, or swap it out for a different role that's specific to a single function\. - -**To create a Ruby function** - -1. Open the [Lambda console](https://console.aws.amazon.com/lambda)\. - -1. Choose **Create function**\. - -1. Configure the following settings: - + **Name** – **my\-function**\. - + **Runtime** – **Ruby 2\.7**\. - + **Role** – **Choose an existing role**\. - + **Existing role** – **lambda\-role**\. - -1. Choose **Create function**\. - -1. To configure a test event, choose **Test**\. - -1. For **Event name**, enter **test**\. - -1. Choose **Create**\. - -1. To execute the function, choose **Test**\. - -The console creates a Lambda function with a single source file named `lambda_function.rb`\. You can edit this file and add more files in the built\-in [code editor](code-editor.md)\. To save your changes, choose **Save**\. Then, to run your code, choose **Test**\. - -**Note** -The Lambda console uses AWS Cloud9 to provide an integrated development environment in the browser\. You can also use AWS Cloud9 to develop Lambda functions in your own environment\. For more information, see [Working with AWS Lambda Functions](https://docs.aws.amazon.com/cloud9/latest/user-guide/lambda-functions.html) in the AWS Cloud9 user guide\. - -The `lambda_function.rb` file exports a function named `lambda_handler` that takes an event object and a context object\. This is the [handler function](ruby-handler.md) that Lambda calls when the function is invoked\. The Ruby function runtime gets invocation events from Lambda and passes them to the handler\. In the function configuration, the handler value is `lambda_function.lambda_handler`\. - -Each time you save your function code, the Lambda console creates a deployment package, which is a ZIP archive that contains your function code\. As your function development progresses, you will want to store your function code in source control, add libraries, and automate deployments\. Start by [creating a deployment package](ruby-package.md) and updating your code at the command line\. - -**Note** -To get started with application development in your local environment, deploy one of the sample applications available in this guide's GitHub repository\. -[blank\-ruby](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/blank-ruby) – A Ruby function that shows the use of logging, environment variables, AWS X\-Ray tracing, layers, unit tests and the AWS SDK\. - -The function runtime passes a context object to the handler, in addition to the invocation event\. The [context object](ruby-context.md) contains additional information about the invocation, the function, and the execution environment\. More information is available from environment variables\. - -Your Lambda function comes with a CloudWatch Logs log group\. The function runtime sends details about each invocation to CloudWatch Logs\. It relays any [logs that your function outputs](ruby-logging.md) during invocation\. If your function [returns an error](ruby-exceptions.md), Lambda formats the error and returns it to the invoker\. - -**Topics** -+ [AWS Lambda function handler in Ruby](ruby-handler.md) -+ [AWS Lambda deployment package in Ruby](ruby-package.md) -+ [AWS Lambda context object in Ruby](ruby-context.md) -+ [AWS Lambda function logging in Ruby](ruby-logging.md) -+ [AWS Lambda function errors in Ruby](ruby-exceptions.md) \ No newline at end of file diff --git a/doc_source/lambda-runtimes.md b/doc_source/lambda-runtimes.md deleted file mode 100644 index 0967ffc6..00000000 --- a/doc_source/lambda-runtimes.md +++ /dev/null @@ -1,80 +0,0 @@ -# AWS Lambda runtimes - -AWS Lambda supports multiple languages through the use of runtimes\. You choose a runtime when you create a function, and you can change runtimes by updating your function's configuration\. The underlying execution environment provides additional libraries and [environment variables](configuration-envvars.md) that you can access from your function code\. - -**Amazon Linux** -+ Image – [amzn\-ami\-hvm\-2018\.03\.0\.20181129\-x86\_64\-gp2](https://console.aws.amazon.com/ec2/v2/home#Images:visibility=public-images;search=amzn-ami-hvm-2018.03.0.20181129-x86_64-gp2) -+ Linux kernel – 4\.14\.171\-105\.231\.amzn1\.x86\_64 - -**Amazon Linux 2** -+ Image – Custom -+ Linux kernel – 4\.14\.165\-102\.205\.amzn2\.x86\_64 - -When your function is invoked, Lambda attempts to re\-use the execution environment from a previous invocation if one is available\. This saves time preparing the execution environment, and allows you to save resources like database connections and temporary files in the [execution context](runtimes-context.md) to avoid creating them every time your function runs\. - -A runtime can support a single version of a language, multiple versions of a language, or multiple languages\. Runtimes specific to a language or framework version are [deprecated](runtime-support-policy.md) when the version reaches end of life\. - - -**Node\.js runtimes** - -| Name | Identifier | AWS SDK for JavaScript | Operating system | -| --- | --- | --- | --- | -| Node\.js 12 | `nodejs12.x` | 2\.631\.0 | Amazon Linux 2 | -| Node\.js 10 | `nodejs10.x` | 2\.631\.0 | Amazon Linux 2 | - - -**Python runtimes** - -| Name | Identifier | AWS SDK for Python | Operating system | -| --- | --- | --- | --- | -| Python 3\.8 | `python3.8` | boto3\-1\.12\.22 botocore\-1\.15\.22 | Amazon Linux 2 | -| Python 3\.7 | `python3.7` | boto3\-1\.12\.22 botocore\-1\.15\.22 | Amazon Linux | -| Python 3\.6 | `python3.6` | boto3\-1\.12\.22 botocore\-1\.15\.22 | Amazon Linux | -| Python 2\.7 | `python2.7` | boto3\-1\.12\.22 botocore\-1\.15\.22 | Amazon Linux | - - -**Ruby runtimes** - -| Name | Identifier | AWS SDK for Ruby | Operating system | -| --- | --- | --- | --- | -| Ruby 2\.7 | `ruby2.7` | 3\.0\.1 | Amazon Linux 2 | -| Ruby 2\.5 | `ruby2.5` | 3\.0\.1 | Amazon Linux | - - -**Java runtimes** - -| Name | Identifier | JDK | Operating system | -| --- | --- | --- | --- | -| Java 11 | `java11` | amazon\-corretto\-11 | Amazon Linux 2 | -| Java 8 | `java8` | java\-1\.8\.0\-openjdk | Amazon Linux | - - -**Go runtimes** - -| Name | Identifier | Operating system | -| --- | --- | --- | -| Go 1\.x | `go1.x` | Amazon Linux | - - -**\.NET runtimes** - -| Name | Identifier | Operating system | -| --- | --- | --- | -| \.NET Core 3\.1 | `dotnetcore3.1` | Amazon Linux 2 | -| \.NET Core 2\.1 | `dotnetcore2.1` | Amazon Linux | - -To use other languages in Lambda, you can implement a [custom runtime](runtimes-custom.md)\. The Lambda execution environment provides a [runtime interface](runtimes-api.md) for getting invocation events and sending responses\. You can deploy a custom runtime alongside your function code, or in a [layer](configuration-layers.md)\. - - -**Custom runtime** - -| Name | Identifier | Operating system | -| --- | --- | --- | -| Custom Runtime | `provided` | Amazon Linux | - -**Topics** -+ [AWS Lambda execution context](runtimes-context.md) -+ [Runtime support policy](runtime-support-policy.md) -+ [Custom AWS Lambda runtimes](runtimes-custom.md) -+ [AWS Lambda runtime interface](runtimes-api.md) -+ [Tutorial – Publishing a custom runtime](runtimes-walkthrough.md) \ No newline at end of file diff --git a/doc_source/lambda-samples.md b/doc_source/lambda-samples.md deleted file mode 100644 index 68e0ddd1..00000000 --- a/doc_source/lambda-samples.md +++ /dev/null @@ -1,62 +0,0 @@ -# Lambda sample applications - -The GitHub repository for this guide includes sample applications that demonstrate the use of various languages and AWS services\. Each sample application includes scripts for easy deployment and cleanup, an AWS SAM template, and supporting resources\. - ------- -#### [ Node\.js ] - -**Sample Lambda applications in Node\.js** -+ [blank\-nodejs](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/blank-nodejs) – A Node\.js function that shows the use of logging, environment variables, AWS X\-Ray tracing, layers, unit tests and the AWS SDK\. -+ [nodejs\-apig](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/nodejs-apig) – A function with a public API endpoint that processes an event from API Gateway and returns an HTTP response\. -+ [rds\-mysql](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/rds-mysql) – A function that relays queries to a MySQL for RDS Database\. This sample includes a private VPC and database instance configured with a password in AWS Secrets Manager\. -+ [list\-manager](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/list-manager) – A function processes events from an Amazon Kinesis data stream and update aggregate lists in Amazon DynamoDB\. The function stores a record of each event in a MySQL for RDS Database in a private VPC\. This sample includes a private VPC with a VPC endpoint for DynamoDB and a database instance\. -+ [error\-processor](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/error-processor) – A Node\.js function generates errors for a specified percentage of requests\. A CloudWatch Logs subscription invokes a second function when an error is recorded\. The processor function uses the AWS SDK to gather details about the request and stores them in an Amazon S3 bucket\. - ------- -#### [ Python ] - -**Sample Lambda applications in Python** -+ [blank\-python](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/blank-python) – A Python function that shows the use of logging, environment variables, AWS X\-Ray tracing, layers, unit tests and the AWS SDK\. - ------- -#### [ Ruby ] - -**Sample Lambda applications in Ruby** -+ [blank\-ruby](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/blank-ruby) – A Ruby function that shows the use of logging, environment variables, AWS X\-Ray tracing, layers, unit tests and the AWS SDK\. - ------- -#### [ Java ] - -**Sample Lambda applications in Java** -+ [blank\-java](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/blank-java) – A Java function that shows the use of Lambda's Java libraries, logging, environment variables, layers, AWS X\-Ray tracing, unit tests, and the AWS SDK\. -+ [java\-basic](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/java-basic) – A minimal Java function with unit tests and variable logging configuration\. -+ [java\-events](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/java-events) – A minimal Java function that uses the [aws\-lambda\-java\-events](java-package.md) library with event types that don't require the AWS SDK as a dependency, such as Amazon API Gateway\. -+ [java\-events\-v1sdk](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/java-events-v1sdk) – A Java function that uses the [aws\-lambda\-java\-events](java-package.md) library with event types that require the AWS SDK as a dependency \(Amazon Simple Storage Service, Amazon DynamoDB, and Amazon Kinesis\)\. -+ [s3\-java](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/s3-java) – A Java function that processes notification events from Amazon S3 and uses the Java Class Library \(JCL\) to create thumbnails from uploaded image files\. - ------- -#### [ Go ] - -**Sample Lambda applications in Go** -+ [blank\-go](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/blank-go) – A Go function that shows the use of Lambda's Go libraries, logging, environment variables, and the AWS SDK\. - ------- -#### [ C\# ] - -**Sample Lambda applications in C\#** -+ [blank\-csharp](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/blank-csharp) – A C\# function that shows the use of Lambda's \.NET libraries, logging, environment variables, AWS X\-Ray tracing, unit tests, and the AWS SDK\. -+ [ec2\-spot](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/ec2-spot) – A function that manages spot instance requests in Amazon EC2\. - ------- -#### [ PowerShell ] - -**Sample Lambda applications in PowerShell** -+ [blank\-powershell](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/blank-powershell) – A PowerShell function that shows the use of logging, environment variables, and the AWS SDK\. - ------- - -To deploy a sample application, follow the instructions in its README file\. To learn more about the architecture and use cases of an application, read the topics in this chapter\. - -**Topics** -+ [Blank function sample application for AWS Lambda](samples-blank.md) -+ [Error processor sample application for AWS Lambda](samples-errorprocessor.md) \ No newline at end of file diff --git a/doc_source/lambda-security.md b/doc_source/lambda-security.md deleted file mode 100644 index ddfc4a94..00000000 --- a/doc_source/lambda-security.md +++ /dev/null @@ -1,17 +0,0 @@ -# Security in AWS Lambda - -Cloud security at AWS is the highest priority\. As an AWS customer, you benefit from a data center and network architecture that is built to meet the requirements of the most security\-sensitive organizations\. - -Security is a shared responsibility between AWS and you\. The [shared responsibility model](http://aws.amazon.com/compliance/shared-responsibility-model/) describes this as security *of* the cloud and security *in* the cloud: -+ **Security of the cloud** – AWS is responsible for protecting the infrastructure that runs AWS services in the AWS Cloud\. AWS also provides you with services that you can use securely\. Third\-party auditors regularly test and verify the effectiveness of our security as part of the [AWS compliance programs](http://aws.amazon.com/compliance/programs/)\. To learn about the compliance programs that apply to AWS Lambda, see [AWS Services in Scope by Compliance Program](http://aws.amazon.com/compliance/services-in-scope/)\. -+ **Security in the cloud** – Your responsibility is determined by the AWS service that you use\. You are also responsible for other factors including the sensitivity of your data, your company’s requirements, and applicable laws and regulations\. - -This documentation helps you understand how to apply the shared responsibility model when using Lambda\. The following topics show you how to configure Lambda to meet your security and compliance objectives\. You also learn how to use other AWS services that help you to monitor and secure your Lambda resources\. - -**Topics** -+ [Data protection in AWS Lambda](security-dataprotection.md) -+ [Identity and access management for AWS Lambda](security-iam.md) -+ [Compliance validation for AWS Lambda](security-compliance.md) -+ [Resilience in AWS Lambda](security-resilience.md) -+ [Infrastructure security in AWS Lambda](security-infrastructure.md) -+ [Configuration and vulnerability analysis in AWS Lambda](security-configuration.md) \ No newline at end of file diff --git a/doc_source/lambda-services.md b/doc_source/lambda-services.md deleted file mode 100644 index fabd706b..00000000 --- a/doc_source/lambda-services.md +++ /dev/null @@ -1,84 +0,0 @@ -# Using AWS Lambda with other services - -AWS Lambda integrates with other AWS services to invoke functions\. You can configure triggers to invoke a function in response to resource lifecycle events, respond to incoming HTTP requests, consume events from a queue, or [run on a schedule](services-cloudwatchevents.md)\. - -Each service that integrates with Lambda sends data to your function in JSON as an event\. The structure of the event document is different for each event type, and contains data about the resource or request that triggered the function\. Lambda runtimes convert the event into an object and pass it to your function\. - -The following example shows a test event from an [Application Load Balancer](services-alb.md) that represents a GET request to `/lambda?query=1234ABCD`\. - -**Example Event from an Application Load Balancer** - -``` -{ - "requestContext": { - "elb": { - "targetGroupArn": "arn:aws:elasticloadbalancing:us-east-2:123456789012:targetgroup/lambda-279XGJDqGZ5rsrHC2Fjr/49e9d65c45c6791a" - } - }, - "httpMethod": "GET", - "path": "/lambda", - "queryStringParameters": { - "query": "1234ABCD" - }, - "headers": { - "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", - "accept-encoding": "gzip", - "accept-language": "en-US,en;q=0.9", - "connection": "keep-alive", - "host": "lambda-alb-123578498.us-east-2.elb.amazonaws.com", - "upgrade-insecure-requests": "1", - "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36", - "x-amzn-trace-id": "Root=1-5c536348-3d683b8b04734faae651f476", - "x-forwarded-for": "72.12.164.125", - "x-forwarded-port": "80", - "x-forwarded-proto": "http", - "x-imforwards": "20" - }, - "body": "", - "isBase64Encoded": false -} -``` - -**Note** -The Lambda runtime converts the event document into an object and passes it to your [function handler](gettingstarted-concepts.md)\. For compiled languages, Lambda provides definitions for event types in a library\. See the following topics for more information\. -[Building Lambda functions with Java](lambda-java.md) -[Building Lambda functions with Go](lambda-golang.md) -[Building Lambda functions with C\#](lambda-csharp.md) -[Building Lambda functions with PowerShell](lambda-powershell.md) - -For services that generate a queue or data stream, you create an [event source mapping](invocation-eventsourcemapping.md) in Lambda and grant Lambda permission to access the other service in the [execution role](lambda-intro-execution-role.md)\. Lambda reads data from the other service, creates an event, and invokes your function\. - -**Services that Lambda reads events from** -+ [Amazon Kinesis](with-kinesis.md) -+ [Amazon DynamoDB](with-ddb.md) -+ [Amazon Simple Queue Service](with-sqs.md) - -Other services invoke your function directly\. You grant the other service permission in the function's [resource\-based policy](access-control-resource-based.md), and configure the other service to generate events and invoke your function\. Depending on the service, the invocation can be synchronous or asynchronous\. For synchronous invocation, the other service waits for the response from your function and might [retry on errors](invocation-retries.md)\. - -**Services that invoke Lambda functions synchronously** -+ [Elastic Load Balancing \(Application Load Balancer\)](services-alb.md) -+ [Amazon Cognito](services-cognito.md) -+ [Amazon Lex](services-lex.md) -+ [Amazon Alexa](services-alexa.md) -+ [Amazon API Gateway](services-apigateway.md) -+ [Amazon CloudFront \(Lambda@Edge\)](lambda-edge.md) -+ [Amazon Kinesis Data Firehose](services-kinesisfirehose.md) -+ [AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/connect-lambda.html) -+ [Amazon Simple Storage Service Batch](services-s3-batch.md) - -For asynchronous invocation, Lambda queues the event before passing it to your function\. The other service gets a success response as soon as the event is queued and isn't aware of what happens afterwards\. If an error occurs, Lambda handles [retries](invocation-retries.md), and can send failed events to a [dead\-letter queue](invocation-async.md#dlq) that you configure\. - -**Services that invoke Lambda functions asynchronously** -+ [Amazon Simple Storage Service](with-s3.md) -+ [Amazon Simple Notification Service](with-sns.md) -+ [Amazon Simple Email Service](services-ses.md) -+ [AWS CloudFormation](services-cloudformation.md) -+ [Amazon CloudWatch Logs](services-cloudwatchlogs.md) -+ [Amazon CloudWatch Events](services-cloudwatchevents.md) -+ [AWS CodeCommit](services-codecommit.md) -+ [AWS Config](services-config.md) -+ [AWS IoT](services-iot.md) -+ [AWS IoT Events](services-iotevents.md) -+ [AWS CodePipeline](services-codepipeline.md) - -See the topics in this chapter for more details about each service, and example events that you can use to test your function\. \ No newline at end of file diff --git a/doc_source/lambda-troubleshooting.md b/doc_source/lambda-troubleshooting.md deleted file mode 100644 index 704883b0..00000000 --- a/doc_source/lambda-troubleshooting.md +++ /dev/null @@ -1,11 +0,0 @@ -# Troubleshooting issues in AWS Lambda - -The following topics provide troubleshooting advice for errors and issues that you might encounter when using the Lambda API, console, or tools\. If you find an issue that is not listed here, you can use the **Feedback** button on this page to report it\. - -For more troubleshooting advice and answers to common support questions, visit the [AWS Knowledge Center](https://aws.amazon.com/premiumsupport/knowledge-center/#AWS_Lambda)\. - -**Topics** -+ [Troubleshoot deployment issues in AWS Lambda](troubleshooting-deployment.md) -+ [Troubleshoot invocation issues in AWS Lambda](troubleshooting-invocation.md) -+ [Troubleshoot execution issues in AWS Lambda](troubleshooting-execution.md) -+ [Troubleshoot networking issues in AWS Lambda](troubleshooting-networking.md) \ No newline at end of file diff --git a/doc_source/lambda-x-ray-daemon.md b/doc_source/lambda-x-ray-daemon.md deleted file mode 100644 index 508d671a..00000000 --- a/doc_source/lambda-x-ray-daemon.md +++ /dev/null @@ -1,8 +0,0 @@ -# The AWS X\-Ray daemon in the Lambda environment - -[The AWS X\-Ray daemon](https://docs.aws.amazon.com/xray/latest/devguide/xray-daemon.html) is a software application that gathers raw segment data and relays it to the AWS X\-Ray service\. The daemon works in conjunction with the AWS X\-Ray SDKs so that data sent by the SDKs can reach the X\-Ray service\. - -When you trace your Lambda function, the X\-Ray daemon automatically runs in the Lambda environment to gather trace data and send it to X\-Ray\. When tracing, the X\-Ray daemon consumes a maximum of 16 MB or 3 percent of your function's memory allocation\. For example, if you allocate 128 MB of memory to your Lambda function, the X\-Ray daemon has 16 MB of your function's memory allocation\. If you allocate 1024 MB to your Lambda function, the X\-Ray daemon has 31 MB allocated to it \(3 percent\)\. For more information, see [The AWS X\-Ray daemon](https://docs.aws.amazon.com/xray/latest/devguide/xray-daemon.html)\. - -**Note** -Lambda will try to terminate the X\-Ray daemon to avoid exceeding your function's memory limit\. For example, assume you have allocated 128 MB to your Lambda function, which means the X\-Ray daemon will have 16 MB allocated to it\. That leaves your Lambda function with a memory allocation of 112 MB\. However, if your function exceeds 112 MB, the X\-Ray daemon will be terminated to avoid throwing an out\-of\-memory error\. \ No newline at end of file diff --git a/doc_source/lambda-x-ray.md b/doc_source/lambda-x-ray.md deleted file mode 100644 index eaff4597..00000000 --- a/doc_source/lambda-x-ray.md +++ /dev/null @@ -1,47 +0,0 @@ -# Using AWS X\-Ray - -You can use AWS X\-Ray to visualize the components of your application, identify performance bottlenecks, and troubleshoot requests that resulted in an error\. Your Lambda functions send trace data to X\-Ray, and X\-Ray processes the data to generate a service map and searchable trace summaries\. - -If you've enabled X\-Ray tracing in a service that invokes your function, Lambda sends traces to X\-Ray automatically\. The upstream service, such as Amazon API Gateway, or an application hosted on Amazon EC2 that is instrumented with the X\-Ray SDK, samples incoming requests and adds a tracing header that tells Lambda to send traces or not\. For a full list of services that support active instrumentation, see [Supported AWS services](https://docs.aws.amazon.com/xray/latest/devguide/xray-usage.html#xray-usage-codechanges) in the AWS X\-Ray Developer Guide\. - -To trace requests that don't have a tracing header, enable active tracing in your function's configuration\. - -You can enable tracing in your function's configuration\. - -**To enable active tracing** - -1. Open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions)\. - -1. Choose a function\. - -1. Under **AWS X\-Ray**, choose **Active tracing**\. - -1. Choose **Save**\. - -Your function needs permission to upload trace data to X\-Ray\. When you enable active tracing in the Lambda console, Lambda adds the required permissions to your function's [execution role](lambda-intro-execution-role.md)\. Otherwise, add the [AWSXRayDaemonWriteAccess](https://console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/AWSXRayDaemonWriteAccess) policy to the execution role\. - -X\-Ray applies a sampling algorithm to ensure that tracing is efficient, while still providing a representative sample of the requests that your application serves\. The default sampling rule is 1 request per second and 5 percent of additional requests\. - -## Using environment variables to communicate with AWS X\-Ray - -AWS Lambda uses environment variables to facilitate communication with the X\-Ray daemon and configure the X\-Ray SDK\. -+ **\_X\_AMZN\_TRACE\_ID:** Contains the tracing header, which includes the sampling decision, trace ID, and parent segment ID\. \(To learn more about these properties, see [Tracing header](https://docs.aws.amazon.com/xray/latest/devguide/xray-concepts.html#xray-concepts-tracingheader)\.\) If Lambda receives a tracing header when your function is invoked, that header will be used to populate the \_X\_AMZN\_TRACE\_ID environment variable\. If a tracing header was not received, Lambda will generate one for you\. -+ **AWS\_XRAY\_CONTEXT\_MISSING:** The X\-Ray SDK uses this variable to determine its behavior in the event that your function tries to record X\-Ray data, but a tracing header is not available\. Lambda sets this value to `LOG_ERROR `by default\. -+ **AWS\_XRAY\_DAEMON\_ADDRESS:** This environment variable exposes the X\-Ray daemon's address in the following format: *IP\_ADDRESS***:***PORT*\. You can use the X\-Ray daemon's address to send trace data to the X\-Ray daemon directly, without using the X\-Ray SDK\. - -## Lambda traces in the AWS X\-Ray console: Examples - -The following shows Lambda traces for two different Lambda functions\. Each trace showcases a trace structure for a different invocation type: asynchronous and synchronous\. -+ **Async ** – The example following shows an asynchronous Lambda request with one successful invocation and one downstream call to DynamoDB\. -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/Trace_Console_DDB.png) - - The Lambda service segment encapsulates the response time, which is the time it took to return a response \(for example, 202\) to the client\. It includes subsegments for the time spent in the Lambda service queue \(dwell time\) and each invocation attempt\. \(Only one invocation attempt appears in the example preceding\.\) Each attempt subsegment in the service segment will have a corresponding user function segment\. In this example, the user function segment contains two subsegments: the initialization subsegment representing the function's initialization code that is run before the handler, and a downstream call subsegment representing a `ListTables` call to DynamoDB\. - - Status codes and error messages are displayed for each Invocation subsegment and for each downstream call\. -+ **Synchronous** – The example following shows a synchronous request with one downstream call to Amazon S3\. -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/Trace_Console_S3.png) - - The Lambda service segment captures the entire time the request spends in the Lambda service\. The service segment will have a corresponding User function segment\. In this example, the User function segment contains a subsegment representing the function's initialization code \(code run before the handler\), and a subsegment representing the `PutObject` call to Amazon S3\. - -**Note** -If you want to trace HTTP calls, you need to use an HTTP client\. For more information, see [Tracing calls to downstream HTTP web services with the X\-Ray SDK for Java](https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-java-httpclients.html) or [Tracing calls to downstream HTTP web services with the X\-Ray SDK for Node\.js ](https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-nodejs-httpclients.html)\. \ No newline at end of file diff --git a/doc_source/logging-using-cloudtrail.md b/doc_source/logging-using-cloudtrail.md deleted file mode 100644 index a08421c3..00000000 --- a/doc_source/logging-using-cloudtrail.md +++ /dev/null @@ -1,114 +0,0 @@ -# Logging AWS Lambda API calls with AWS CloudTrail - -AWS Lambda is integrated with AWS CloudTrail, a service that provides a record of actions taken by a user, role, or an AWS service in AWS Lambda\. CloudTrail captures API calls for AWS Lambda as events\. The calls captured include calls from the AWS Lambda console and code calls to the AWS Lambda API operations\. If you create a trail, you can enable continuous delivery of CloudTrail events to an Amazon S3 bucket, including events for AWS Lambda\. If you don't configure a trail, you can still view the most recent events in the CloudTrail console in **Event history**\. Using the information collected by CloudTrail, you can determine the request that was made to AWS Lambda, the IP address from which the request was made, who made the request, when it was made, and additional details\. - -To learn more about CloudTrail, including how to configure and enable it, see the [AWS CloudTrail User Guide](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/)\. - -## AWS Lambda information in CloudTrail - -CloudTrail is enabled on your AWS account when you create the account\. When supported event activity occurs in AWS Lambda, that activity is recorded in a CloudTrail event along with other AWS service events in **Event history**\. You can view, search, and download recent events in your AWS account\. For more information, see [Viewing events with CloudTrail event history](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/view-cloudtrail-events.html)\. - -For an ongoing record of events in your AWS account, including events for AWS Lambda, you create a trail\. A *trail* enables CloudTrail to deliver log files to an Amazon S3 bucket\. By default, when you create a trail in the console, the trail applies to all AWS Regions\. The trail logs events from all Regions in the AWS partition and delivers the log files to the Amazon S3 bucket that you specify\. Additionally, you can configure other AWS services to further analyze and act upon the event data collected in CloudTrail logs\. For more information, see the following: -+ [Overview for creating a trail](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-create-and-update-a-trail.html) -+ [CloudTrail supported services and integrations](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-aws-service-specific-topics.html#cloudtrail-aws-service-specific-topics-integrations) -+ [Configuring Amazon SNS notifications for CloudTrail](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/getting_notifications_top_level.html) -+ [Receiving CloudTrail log files from multiple regions](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/receive-cloudtrail-log-files-from-multiple-regions.html) and [Receiving CloudTrail log files from multiple accounts](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-receive-logs-from-multiple-accounts.html) - -AWS Lambda supports logging the following actions as events in CloudTrail log files: -+ [AddPermission](API_AddPermission.md) -+ [CreateEventSourceMapping](API_CreateEventSourceMapping.md) -+ [CreateFunction](API_CreateFunction.md) - - \(The `ZipFile` parameter is omitted from the CloudTrail logs for `CreateFunction`\.\) -+ [DeleteEventSourceMapping](API_DeleteEventSourceMapping.md) -+ [DeleteFunction](API_DeleteFunction.md) -+ [GetEventSourceMapping](API_GetEventSourceMapping.md) -+ [GetFunction](API_GetFunction.md) -+ [GetFunctionConfiguration](API_GetFunctionConfiguration.md) -+ [GetPolicy](API_GetPolicy.md) -+ [ListEventSourceMappings](API_ListEventSourceMappings.md) -+ [ListFunctions](API_ListFunctions.md) -+ [RemovePermission](API_RemovePermission.md) -+ [UpdateEventSourceMapping](API_UpdateEventSourceMapping.md) -+ [UpdateFunctionCode](API_UpdateFunctionCode.md) - - \(The `ZipFile` parameter is omitted from the CloudTrail logs for `UpdateFunctionCode`\.\) -+ [UpdateFunctionConfiguration](API_UpdateFunctionConfiguration.md) - -Every log entry contains information about who generated the request\. The user identity information in the log helps you determine whether the request was made with root or IAM user credentials, with temporary security credentials for a role or federated user, or by another AWS service\. For more information, see the **userIdentity** field in the [CloudTrail event reference](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-event-reference.html)\. - -You can store your log files in your bucket for as long as you want, but you can also define Amazon S3 lifecycle rules to archive or delete log files automatically\. By default, your log files are encrypted by using Amazon S3 server\-side encryption \(SSE\)\. - -You can choose to have CloudTrail publish Amazon SNS notifications when new log files are delivered if you want to take quick action upon log file delivery\. For more information, see [Configuring Amazon SNS notifications for CloudTrail](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/configure-sns-notifications-for-cloudtrail.html)\. - -You can also aggregate AWS Lambda log files from multiple AWS regions and multiple AWS accounts into a single S3 bucket\. For more information, see [Working with CloudTrail log files](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-working-with-log-files.html)\. - -## Understanding AWS Lambda log file entries - -CloudTrail log files contain one or more log entries where each entry is made up of multiple JSON\-formatted events\. A log entry represents a single request from any source and includes information about the requested action, any parameters, the date and time of the action, and so on\. The log entries are not guaranteed to be in any particular order\. That is, they are not an ordered stack trace of the public API calls\. - -The following example shows CloudTrail log entries for the `GetFunction` and `DeleteFunction` actions\. - -``` -{ - "Records": [ - { - "eventVersion": "1.03", - "userIdentity": { - "type": "IAMUser", - "principalId": "A1B2C3D4E5F6G7EXAMPLE", - "arn": "arn:aws:iam::999999999999:user/myUserName", - "accountId": "999999999999", - "accessKeyId": "AKIAIOSFODNN7EXAMPLE", - "userName": "myUserName" - }, - "eventTime": "2015-03-18T19:03:36Z", - "eventSource": "lambda.amazonaws.com", - "eventName": "GetFunction", - "awsRegion": "us-east-1", - "sourceIPAddress": "127.0.0.1", - "userAgent": "Python-httplib2/0.8 (gzip)", - "errorCode": "AccessDenied", - "errorMessage": "User: arn:aws:iam::999999999999:user/myUserName is not authorized to perform: lambda:GetFunction on resource: arn:aws:lambda:us-west-2:999999999999:function:other-acct-function", - "requestParameters": null, - "responseElements": null, - "requestID": "7aebcd0f-cda1-11e4-aaa2-e356da31e4ff", - "eventID": "e92a3e85-8ecd-4d23-8074-843aabfe89bf", - "eventType": "AwsApiCall", - "recipientAccountId": "999999999999" - }, - { - "eventVersion": "1.03", - "userIdentity": { - "type": "IAMUser", - "principalId": "A1B2C3D4E5F6G7EXAMPLE", - "arn": "arn:aws:iam::999999999999:user/myUserName", - "accountId": "999999999999", - "accessKeyId": "AKIAIOSFODNN7EXAMPLE", - "userName": "myUserName" - }, - "eventTime": "2015-03-18T19:04:42Z", - "eventSource": "lambda.amazonaws.com", - "eventName": "DeleteFunction", - "awsRegion": "us-east-1", - "sourceIPAddress": "127.0.0.1", - "userAgent": "Python-httplib2/0.8 (gzip)", - "requestParameters": { - "functionName": "basic-node-task" - }, - "responseElements": null, - "requestID": "a2198ecc-cda1-11e4-aaa2-e356da31e4ff", - "eventID": "20b84ce5-730f-482e-b2b2-e8fcc87ceb22", - "eventType": "AwsApiCall", - "recipientAccountId": "999999999999" - } - ] -} -``` - -**Note** -The `eventName` may include date and version information, such as `"GetFunction20150331"`, but it is still referring to the same public API\. For more information, see [ Services supported by CloudTrail event history](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/view-cloudtrail-events-supported-services.html#view-cloudtrail-events-supported-apis-lambda) in the *AWS CloudTrail User Guide*\. - -## Using CloudTrail to track function invocations - -CloudTrail also logs data events\. You can turn on data event logging so that you log an event every time Lambda functions are invoked\. This helps you understand what identities are invoking the functions and the frequency of their invocations\. For more information on this option, see [ Logging data events for trails](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/logging-data-events-with-cloudtrail.html)\. \ No newline at end of file diff --git a/doc_source/monitoring-cloudwatchlogs.md b/doc_source/monitoring-cloudwatchlogs.md deleted file mode 100644 index 9660a4f7..00000000 --- a/doc_source/monitoring-cloudwatchlogs.md +++ /dev/null @@ -1,25 +0,0 @@ -# Accessing Amazon CloudWatch logs for AWS Lambda - -AWS Lambda automatically monitors Lambda functions on your behalf, reporting metrics through Amazon CloudWatch\. To help you troubleshoot failures in a function, Lambda logs all requests handled by your function and also automatically stores logs generated by your code through Amazon CloudWatch Logs\. - -You can insert logging statements into your code to help you validate that your code is working as expected\. Lambda automatically integrates with CloudWatch Logs and pushes all logs from your code to a CloudWatch Logs group associated with a Lambda function, which is named /aws/lambda/**\. To learn more about log groups and accessing them through the CloudWatch console, see the [Monitoring system, application, and custom log files](https://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/WhatIsCloudWatchLogs.html) in the *Amazon CloudWatch User Guide*\. - -You can view logs for Lambda by using the Lambda console, the CloudWatch console, the AWS CLI, or the CloudWatch API\. The following procedure show you how to view the logs by using the Lambda console\. - -**Note** -There is no additional charge for using Lambda logs; however, standard CloudWatch Logs charges apply\. For more information, see [CloudWatch pricing\.](https://aws.amazon.com/cloudwatch/pricing/) - -**To view logs using the Lambda console** - -1. Open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions)\. - -1. Choose a function\. - -1. Choose **Monitoring**\. -![\[Events\]](http://docs.aws.amazon.com/lambda/latest/dg/images/metrics-functions-list.png)![\[Events\]](http://docs.aws.amazon.com/lambda/latest/dg/)![\[Events\]](http://docs.aws.amazon.com/lambda/latest/dg/) - - A graphical representation of the metrics for the Lambda function are shown\. - -1. Choose **View logs in CloudWatch**\. - -Lambda uses your function's permissions to upload logs to CloudWatch Logs\. If you don't see logs in the console, check your [execution role permissions](lambda-intro-execution-role.md)\. \ No newline at end of file diff --git a/doc_source/monitoring-functions-access-metrics.md b/doc_source/monitoring-functions-access-metrics.md deleted file mode 100644 index 6045fd11..00000000 --- a/doc_source/monitoring-functions-access-metrics.md +++ /dev/null @@ -1,31 +0,0 @@ -# Monitoring functions in the AWS Lambda console - -AWS Lambda monitors functions on your behalf and sends metrics to Amazon CloudWatch\. The metrics include total requests, duration, and error rates\. The Lambda console creates graphs for these metrics and shows them on the **Monitoring** page for each function\. - -**To access the monitoring console** - -1. Open the [Lambda console](https://console.aws.amazon.com/lambda)\. - -1. Open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions)\. - -1. Choose **Monitoring**\. -![\[Graphs of various CloudWatch metrics.\]](http://docs.aws.amazon.com/lambda/latest/dg/images/metrics-functions-list.png) - -The console provides the following graphs\. - -**Lambda monitoring graphs** -+ **Invocations** – The number of times that the function was invoked in each 5\-minute period\. -+ **Duration** – The average, minimum, and maximum execution times\. -+ **Error count and success rate \(%\)** – The number of errors and the percentage of executions that completed without error\. -+ **Throttles** – The number of times that execution failed due to concurrency limits\. -+ **IteratorAge** – For stream event sources, the age of the last item in the batch when Lambda received it and invoked the function\. -+ **Async delivery failures** – The number of errors that occurred when Lambda attempted to write to a destination or dead\-letter queue\. -+ **Concurrent executions** – The number of function instances that are processing events\. - -To see the definition of a graph in CloudWatch, choose **View in metrics** from the menu in the top right of the graph\. For more information about the metrics that Lambda records, see [Working with AWS Lambda function metrics](monitoring-metrics.md)\. - -The console also shows reports from CloudWatch Logs Insights that are compiled from information in your function's logs\. You can add these reports to a custom dashboard in the CloudWatch Logs console\. Use the queries as a starting point for your own reports\. - -![\[AWS CloudWatch Logs Insights reports\]](http://docs.aws.amazon.com/lambda/latest/dg/images/console-monitoring-insights.png) - -To view a query, choose **View in CloudWatch Logs Insights** from the menu in the top right of the report\. \ No newline at end of file diff --git a/doc_source/monitoring-metrics.md b/doc_source/monitoring-metrics.md deleted file mode 100644 index a1217437..00000000 --- a/doc_source/monitoring-metrics.md +++ /dev/null @@ -1,61 +0,0 @@ -# Working with AWS Lambda function metrics - -When your function finishes processing an event, Lambda sends metrics about the invocation to Amazon CloudWatch\. You can build graphs and dashboards with these metrics in the CloudWatch console, and set alarms to respond to changes in utilization, performance, or error rates\. Use dimensions to filter and sort function metrics by function name, alias, or version\. - -**To view metrics in the CloudWatch console** - -1. Open the [Amazon CloudWatch console Metrics page](https://console.aws.amazon.com/cloudwatch/home?region=us-east-1#metricsV2:graph=~();namespace=~'AWS*2fLambda) \(`AWS/Lambda` namespace\)\. - -1. Choose a dimension\. - + **By Function Name** \(`FunctionName`\) – View aggregate metrics for all versions and aliases of a function\. - + **By Resource** \(`Resource`\) – View metrics for a version or alias of a function\. - + **By Executed Version** \(`ExecutedVersion`\) – View metrics for a combination of alias and version\. Use the `ExecutedVersion` dimension to compare error rates for two versions of a function that are both targets of a [weighted alias](configuration-aliases.md)\. - + **Across All Functions** \(none\) – View aggregate metrics for all functions in the current AWS Region\. - -1. Choose metrics to add them to the graph\. - -By default, graphs use the `Sum` statistic for all metrics\. To choose a different statistic and customize the graph, use the options on the **Graphed metrics** tab\. - -The timestamp on a metric reflects when the function was invoked\. Depending on the duration of the execution, this can be several minutes before the metric is emitted\. If, for example, your function has a 10\-minute timeout, look more than 10 minutes in the past for accurate metrics\. - -For more information about CloudWatch, see the [https://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/](https://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/)\. - -**Topics** -+ [Using invocation metrics](#monitoring-metrics-invocation) -+ [Using performance metrics](#monitoring-metrics-performance) -+ [Using concurrency metrics](#monitoring-metrics-concurrency) - -## Using invocation metrics - -Invocation metrics are binary indicators of the outcome of an invocation\. For example, if the function returns an error, Lambda sends the `Errors` metric with a value of 1\. To get a count of the number of function errors that occurred each minute, view the sum of the `Errors` metric with a period of one minute\. - -You should view the following metrics with the `Sum` statistic\. - -**Invocation metrics** -+ `Invocations` – The number of times your function code is executed, including successful executions and executions that result in a function error\. Invocations aren't recorded if the invocation request is throttled or otherwise resulted in an [invocation error](API_Invoke.md#API_Invoke_Errors)\. This equals the number of requests billed\. -+ `Errors` – The number of invocations that result in a function error\. Function errors include exceptions thrown by your code and exceptions thrown by the Lambda runtime\. The runtime returns errors for issues such as timeouts and configuration errors\. To calculate the error rate, divide the value of `Errors` by the value of `Invocations`\. -+ `DeadLetterErrors` – For [asynchronous invocation](invocation-async.md), the number of times Lambda attempts to send an event to a dead\-letter queue but fails\. Dead\-letter errors can occur due to permissions errors, misconfigured resources, or size limits\. -+ `DestinationDeliveryFailures` – For asynchronous invocation, the number of times Lambda attempts to send an event to a [destination](gettingstarted-features.md#gettingstarted-features-destinations) but fails\. Delivery errors can occur due to permissions errors, misconfigured resources, or size limits\. -+ `Throttles` – The number of invocation requests that are throttled\. When all function instances are processing requests and no concurrency is available to scale up, Lambda rejects additional requests with [TooManyRequestsException](API_Invoke.md#API_Invoke_Errors)\. Throttled requests and other invocation errors don't count as `Invocations` or `Errors`\. -+ `ProvisionedConcurrencyInvocations` – The number of times your function code is executed on [provisioned concurrency](configuration-concurrency.md)\. -+ `ProvisionedConcurrencySpilloverInvocations` – The number of times your function code is executed on standard concurrency when all provisioned concurrency is in use\. - -## Using performance metrics - -Performance metrics provide performance details about a single invocation\. For example, the `Duration` metric indicates the amount of time in milliseconds that your function spends processing an event\. To get a sense of how fast your function processes events, view these metrics with the `Average` or `Maximum` statistic\. - -**Performance metrics** -+ `Duration` – The amount of time that your function code spends processing an event\. For the first event processed by an instance of your function, this includes [initialization time](gettingstarted-features.md#gettingstarted-features-programmingmodel)\. The billed duration for an invocation is the value of `Duration` rounded up to the nearest 100 milliseconds\. -+ `IteratorAge` – For [event source mappings](invocation-eventsourcemapping.md) that read from streams, the age of the last record in the event\. The age is the amount of time between when the stream receives the record and when the event source mapping sends the event to the function\. - -`Duration` also supports [percentile statistics](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Percentiles)\. Use percentiles to exclude outlier values that skew average and maximum statistics\. For example, the P95 statistic shows the maximum duration of 95 percent of executions, excluding the slowest 5 percent\. - -## Using concurrency metrics - -Lambda reports concurrency metrics as an aggregate count of the number of instances processing events across a function, version, alias, or AWS Region\. To see how close you are to hitting concurrency limits, view these metrics with the `Max` statistic\. - -**Concurrency metrics** -+ `ConcurrentExecutions` – The number of function instances that are processing events\. If this number reaches your [concurrent executions limit](gettingstarted-limits.md) for the Region, or the [reserved concurrency limit](configuration-concurrency.md) that you configured on the function, additional invocation requests are throttled\. -+ `ProvisionedConcurrentExecutions` – The number of function instances that are processing events on [provisioned concurrency](configuration-concurrency.md)\. For each invocation of an alias or version with provisioned concurrency, Lambda emits the current count\. -+ `ProvisionedConcurrencyUtilization` – For a version or alias, the value of `ProvisionedConcurrentExecutions` divided by the total amount of provisioned concurrency allocated\. For example, `.5` indicates that 50 percent of allocated provisioned concurrency is in use\. -+ `UnreservedConcurrentExecutions` – For an AWS Region, the number of events that are being processed by functions that don't have reserved concurrency\. \ No newline at end of file diff --git a/doc_source/nodejs-context.md b/doc_source/nodejs-context.md deleted file mode 100644 index a89e311d..00000000 --- a/doc_source/nodejs-context.md +++ /dev/null @@ -1,43 +0,0 @@ -# AWS Lambda context object in Node\.js - -When Lambda runs your function, it passes a context object to the [handler](nodejs-handler.md)\. This object provides methods and properties that provide information about the invocation, function, and execution environment\. - -**Context methods** -+ `getRemainingTimeInMillis()` – Returns the number of milliseconds left before the execution times out\. - -**Context properties** -+ `functionName` – The name of the Lambda function\. -+ `functionVersion` – The [version](configuration-versions.md) of the function\. -+ `invokedFunctionArn` – The Amazon Resource Name \(ARN\) that's used to invoke the function\. Indicates if the invoker specified a version number or alias\. -+ `memoryLimitInMB` – The amount of memory that's allocated for the function\. -+ `awsRequestId` – The identifier of the invocation request\. -+ `logGroupName` – The log group for the function\. -+ `logStreamName` – The log stream for the function instance\. -+ `identity` – \(mobile apps\) Information about the Amazon Cognito identity that authorized the request\. - + `cognitoIdentityId` – The authenticated Amazon Cognito identity\. - + `cognitoIdentityPoolId` – The Amazon Cognito identity pool that authorized the invocation\. -+ `clientContext` – \(mobile apps\) Client context that's provided to Lambda by the client application\. - + `client.installation_id` - + `client.app_title` - + `client.app_version_name` - + `client.app_version_code` - + `client.app_package_name` - + `env.platform_version` - + `env.platform` - + `env.make` - + `env.model` - + `env.locale` - + `Custom` – Custom values that are set by the mobile application\. -+ `callbackWaitsForEmptyEventLoop` – Set to false to send the response right away when the [callback](nodejs-handler.md#nodejs-handler-sync) executes, instead of waiting for the Node\.js event loop to be empty\. If this is false, any outstanding events continue to run during the next invocation\. - -The following example function logs context information and returns the location of the logs\. - -**Example index\.js file** - -``` -exports.handler = async function(event, context) { - console.log('Remaining time: ', context.getRemainingTimeInMillis()) - console.log('Function name: ', context.functionName) - return context.logStreamName -} -``` \ No newline at end of file diff --git a/doc_source/nodejs-exceptions.md b/doc_source/nodejs-exceptions.md deleted file mode 100644 index b1db8be0..00000000 --- a/doc_source/nodejs-exceptions.md +++ /dev/null @@ -1,62 +0,0 @@ -# AWS Lambda function errors in Node\.js - -When your code raises an error, Lambda generates a JSON representation of the error\. This error document appears in the invocation log and, for synchronous invocations, in the output\. - -**Example index\.js file – Reference error** - -``` -exports.handler = async function() { - return x + 10 -} -``` - -This code results in a reference error\. Lambda catches the error and generates a JSON document with fields for the error message, the type, and the stack trace\. - -``` -{ - "errorType": "ReferenceError", - "errorMessage": "x is not defined", - "trace": [ - "ReferenceError: x is not defined", - " at Runtime.exports.handler (/var/task/index.js:2:3)", - " at Runtime.handleOnce (/var/runtime/Runtime.js:63:25)", - " at process._tickCallback (internal/process/next_tick.js:68:7)" - ] -} -``` - -When you invoke the function from the command line, the AWS CLI splits the response into two documents\. To indicate that a function error occurred, the response displayed in the terminal includes a `FunctionError` field\. The response or error returned by the function is written to the output file\. - -``` -$ aws lambda invoke --function-name my-function out.json -{ - "StatusCode": 200, - "FunctionError": "Unhandled", - "ExecutedVersion": "$LATEST" -} -``` - -View the output file to see the error document\. - -``` -$ cat out.json -{"errorType":"ReferenceError","errorMessage":"x is not defined","trace":["ReferenceError: x is not defined"," at Runtime.exports.handler (/var/task/index.js:2:3)"," at Runtime.handleOnce (/var/runtime/Runtime.js:63:25)"," at process._tickCallback (internal/process/next_tick.js:68:7)"]} -``` - -**Note** -The 200 \(success\) status code in the response from Lambda indicates that there wasn't an error with the request that you sent to Lambda\. For issues that result in an error status code, see [Errors](API_Invoke.md#API_Invoke_Errors)\. - -Lambda also records up to 256 KB of the error object in the function's logs\. To view logs when you invoke the function from the command line, use the `--log-type` option and decode the base64 string in the response\. - -``` -$ aws lambda invoke --function-name my-function out.json --log-type Tail \ ---query 'LogResult' --output text | base64 -d -START RequestId: 8bbbfb91-a3ff-4502-b1b7-cb8f6658de64 Version: $LATEST -2019-06-05T22:11:27.082Z 8bbbfb91-a3ff-4502-b1b7-cb8f6658de64 ERROR Invoke Error {"errorType":"ReferenceError","errorMessage":"x is not defined","stack":["ReferenceError: x is not defined"," at Runtime.exports.handler (/var/task/index.js:2:3)"," at Runtime.handleOnce (/var/runtime/Runtime.js:63:25)"," at process._tickCallback (internal/process/next_tick.js:68:7)"]} -END RequestId: 8bbbfb91-a3ff-4502-b1b7-cb8f6658de64 -REPORT RequestId: 8bbbfb91-a3ff-4502-b1b7-cb8f6658de64 Duration: 76.85 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 74 MB -``` - -For more information about logs, see [AWS Lambda function logging in Node\.js](nodejs-logging.md)\. - -Depending on the event source, AWS Lambda might retry the failed Lambda function\. For example, if Kinesis is the event source, AWS Lambda retries the failed invocation until the Lambda function succeeds or the records in the stream expire\. For more information on retries, see [Error handling and automatic retries in AWS Lambda](invocation-retries.md)\. \ No newline at end of file diff --git a/doc_source/nodejs-handler.md b/doc_source/nodejs-handler.md deleted file mode 100644 index 815f5694..00000000 --- a/doc_source/nodejs-handler.md +++ /dev/null @@ -1,99 +0,0 @@ -# AWS Lambda function handler in Node\.js - -The handler is the method in your Lambda function that processes events\. When you invoke a function, the [runtime](lambda-runtimes.md) runs the handler method\. When the handler exits or returns a response, it becomes available to handle another event\. - -The following example function logs the contents of the event object and returns the location of the logs\. - -**Example index\.js** - -``` -exports.handler = async function(event, context) { - console.log("EVENT: \n" + JSON.stringify(event, null, 2)) - return context.logStreamName -} -``` - -When you [configure a function](configuration-console.md), the value of the handler setting is the file name and the name of the exported handler module, separated by a dot\. The default in the console and for examples in this guide is `index.handler`\. This indicates the `handler` module that's exported by `index.js`\. - -The runtime passes three arguments to the handler method\. The first argument is the `event` object, which contains information from the invoker\. The invoker passes this information as a JSON\-formatted string when it calls [Invoke](API_Invoke.md), and the runtime converts it to an object\. When an AWS service invokes your function, the event structure [varies by service](lambda-services.md)\. - -The second argument is the [context object](nodejs-context.md), which contains information about the invocation, function, and execution environment\. In the preceding example, the function gets the name of the [log stream](nodejs-logging.md) from the context object and returns it to the invoker\. - -The third argument, `callback`, is a function that you can call in [non\-async handlers](#nodejs-handler-sync) to send a response\. The callback function takes two arguments: an `Error` and a response\. When you call it, Lambda waits for the event loop to be empty and then returns the response or error to the invoker\. The response object must be compatible with `JSON.stringify`\. - -For async handlers, you return a response, error, or promise to the runtime instead of using `callback`\. - -## Async handlers - -For async handlers, you can use `return` and `throw` to send a response or error, respectively\. Functions must use the `async` keyword to use these methods to return a response or error\. - -If your code performs an asynchronous task, return a promise to make sure that it finishes running\. When you resolve or reject the promise, Lambda sends the response or error to the invoker\. - -**Example index\.js file – HTTP request with async handler and promises** - -``` -const https = require('https') -let url = "https://docs.aws.amazon.com/lambda/latest/dg/welcome.html" - -exports.handler = async function(event) { - const promise = new Promise(function(resolve, reject) { - https.get(url, (res) => { - resolve(res.statusCode) - }).on('error', (e) => { - reject(Error(e)) - }) - }) - return promise -} -``` - -For libraries that return a promise, you can return that promise directly to the runtime\. - -**Example index\.js file – AWS SDK with async handler and promises** - -``` -const AWS = require('aws-sdk') -const s3 = new AWS.S3() - -exports.handler = async function(event) { - return s3.listBuckets().promise() -} -``` - -## Non\-async handlers - -The following example function checks a URL and returns the status code to the invoker\. - -**Example index\.js file – HTTP request with callback** - -``` -const https = require('https') -let url = "https://docs.aws.amazon.com/lambda/latest/dg/welcome.html" - -exports.handler = function(event, context, callback) { - https.get(url, (res) => { - callback(null, res.statusCode) - }).on('error', (e) => { - callback(Error(e)) - }) -} -``` - -For non\-async handlers, function execution continues until the [event loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/) is empty or the function times out\. The response isn't sent to the invoker until all event loop tasks are finished\. If the function times out, an error is returned instead\. You can configure the runtime to send the response immediately by setting [context\.callbackWaitsForEmptyEventLoop](nodejs-context.md) to false\. - -In the following example, the response from Amazon S3 is returned to the invoker as soon as it's available\. The timeout running on the event loop is frozen, and it continues running the next time the function is invoked\. - -**Example index\.js file – callbackWaitsForEmptyEventLoop** - -``` -const AWS = require('aws-sdk') -const s3 = new AWS.S3() - -exports.handler = function(event, context, callback) { - context.callbackWaitsForEmptyEventLoop = false - s3.listBuckets(null, callback) - setTimeout(function () { - console.log('Timeout complete.') - }, 5000) -} -``` \ No newline at end of file diff --git a/doc_source/nodejs-logging.md b/doc_source/nodejs-logging.md deleted file mode 100644 index 9f4725f0..00000000 --- a/doc_source/nodejs-logging.md +++ /dev/null @@ -1,158 +0,0 @@ -# AWS Lambda function logging in Node\.js - -Your Lambda function comes with a CloudWatch Logs log group, with a log stream for each instance of your function\. The runtime sends details about each invocation to the log stream, and relays logs and other output from your function's code\. - -To output logs from your function code, you can use methods on the [console object](https://developer.mozilla.org/en-US/docs/Web/API/Console), or any logging library that writes to `stdout` or `stderr`\. The following example logs the values of environment variables and the event object\. - -**Example index\.js file – Logging** - -``` -exports.handler = async function(event, context) { - console.log("ENVIRONMENT VARIABLES\n" + JSON.stringify(process.env, null, 2)) - console.info("EVENT\n" + JSON.stringify(event, null, 2)) - console.warn("Event not processed.") - return context.logStreamName -} -``` - -**Example Log format** - -``` -START RequestId: c793869b-ee49-115b-a5b6-4fd21e8dedac Version: $LATEST -2019-06-07T19:11:20.562Z c793869b-ee49-115b-a5b6-4fd21e8dedac INFO ENVIRONMENT VARIABLES -{ - "AWS_LAMBDA_FUNCTION_VERSION": "$LATEST", - "AWS_LAMBDA_LOG_GROUP_NAME": "/aws/lambda/my-function", - "AWS_LAMBDA_LOG_STREAM_NAME": "2019/06/07/[$LATEST]e6f4a0c4241adcd70c262d34c0bbc85c", - "AWS_EXECUTION_ENV": "AWS_Lambda_nodejs12.x", - "AWS_LAMBDA_FUNCTION_NAME": "my-function", - "PATH": "/var/lang/bin:/usr/local/bin:/usr/bin/:/bin:/opt/bin", - "NODE_PATH": "/opt/nodejs/node10/node_modules:/opt/nodejs/node_modules:/var/runtime/node_modules", - ... -} -2019-06-07T19:11:20.563Z c793869b-ee49-115b-a5b6-4fd21e8dedac INFO EVENT -{ - "key": "value" -} -2019-06-07T19:11:20.564Z c793869b-ee49-115b-a5b6-4fd21e8dedac WARN Event not processed. -END RequestId: c793869b-ee49-115b-a5b6-4fd21e8dedac -REPORT RequestId: c793869b-ee49-115b-a5b6-4fd21e8dedac Duration: 128.83 ms Billed Duration: 200 ms Memory Size: 128 MB Max Memory Used: 74 MB Init Duration: 166.62 ms XRAY TraceId: 1-5d9d007f-0a8c7fd02xmpl480aed55ef0 SegmentId: 3d752xmpl1bbe37e Sampled: true -``` - -The Node\.js runtime logs the `START`, `END`, and `REPORT` lines for each invocation\. It adds a timestamp, request ID, and log level to each entry logged by the function\. The report line provides the following details\. - -**Report Log** -+ **RequestId** – The unique request ID for the invocation\. -+ **Duration** – The amount of time that your function's handler method spent processing the event\. -+ **Billed Duration** – The amount of time billed for the invocation\. -+ **Memory Size** – The amount of memory allocated to the function\. -+ **Max Memory Used** – The amount of memory used by the function\. -+ **Init Duration** – For the first request served, the amount of time it took the runtime to load the function and run code outside of the handler method\. -+ **XRAY TraceId** – For traced requests, the [AWS X\-Ray trace ID](lambda-x-ray.md)\. -+ **SegmentId** – For traced requests, the X\-Ray segment ID\. -+ **Sampled** – For traced requests, the sampling result\. - -You can view logs in the Lambda console, in the CloudWatch Logs console, or from the command line\. - -**Topics** -+ [Viewing logs in the AWS Management Console](#nodejs-logging-console) -+ [Using the AWS CLI](#nodejs-logging-cli) -+ [Deleting logs](#nodejs-logging-delete) - -## Viewing logs in the AWS Management Console - -The Lambda console shows log output when you test a function on the function configuration page\. To view logs for all invocations, use the CloudWatch Logs console\. - -**To view your Lambda function's logs** - -1. Open the [Logs page of the CloudWatch console](https://console.aws.amazon.com/cloudwatch/home?#logs:)\. - -1. Choose the log group for your function \(**/aws/lambda/*function\-name***\)\. - -1. Choose the first stream in the list\. - -Each log stream corresponds to an [instance of your function](runtimes-context.md)\. New streams appear when you update your function and when additional instances are created to handle multiple concurrent invocations\. To find logs for specific invocations, you can instrument your function with X\-Ray, and record details about the request and log stream in the trace\. For a sample application that correlates logs and traces with X\-Ray, see [Error processor sample application for AWS Lambda](samples-errorprocessor.md)\. - -## Using the AWS CLI - -To get logs for an invocation from the command line, use the `--log-type` option\. The response includes a `LogResult` field that contains up to 4 KB of base64\-encoded logs from the invocation\. - -``` -$ aws lambda invoke --function-name my-function out --log-type Tail -{ - "StatusCode": 200, - "LogResult": "U1RBUlQgUmVxdWVzdElkOiA4N2QwNDRiOC1mMTU0LTExZTgtOGNkYS0yOTc0YzVlNGZiMjEgVmVyc2lvb...", - "ExecutedVersion": "$LATEST" -} -``` - -You can use the `base64` utility to decode the logs\. - -``` -$ aws lambda invoke --function-name my-function out --log-type Tail \ ---query 'LogResult' --output text | base64 -d -START RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 Version: $LATEST - "AWS_SESSION_TOKEN": "AgoJb3JpZ2luX2VjELj...", "_X_AMZN_TRACE_ID": "Root=1-5d02e5ca-f5792818b6fe8368e5b51d50;Parent=191db58857df8395;Sampled=0"",ask/lib:/opt/lib", -END RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 -REPORT RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 Duration: 79.67 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 73 MB -``` - -The `base64` utility is available on Linux, macOS, and [Ubuntu on Windows](https://docs.microsoft.com/en-us/windows/wsl/install-win10)\. For macOS, the command is `base64 -D`\. - -To get full log events from the command line, you can include the log stream name in the output of your function, as shown in the preceding example\. The following example script invokes a function named `my-function` and downloads the last five log events\. - -**Example get\-logs\.sh Script** -This example requires that `my-function` returns a log stream ID\. - -``` -#!/bin/bash -aws lambda invoke --function-name my-function --payload '{"key": "value"}' out -sed -i'' -e 's/"//g' out -sleep 15 -aws logs get-log-events --log-group-name /aws/lambda/my-function --log-stream-name $(cat out) --limit 5 -``` - -The script uses `sed` to remove quotes from the output file, and sleeps for 15 seconds to allow time for the logs to be available\. The output includes the response from Lambda and the output from the `get-log-events` command\. - -``` -$ ./get-logs.sh -{ - "StatusCode": 200, - "ExecutedVersion": "$LATEST" -} -{ - "events": [ - { - "timestamp": 1559763003171, - "message": "START RequestId: 4ce9340a-b765-490f-ad8a-02ab3415e2bf Version: $LATEST\n", - "ingestionTime": 1559763003309 - }, - { - "timestamp": 1559763003173, - "message": "2019-06-05T19:30:03.173Z\t4ce9340a-b765-490f-ad8a-02ab3415e2bf\tINFO\tENVIRONMENT VARIABLES\r{\r \"AWS_LAMBDA_FUNCTION_VERSION\": \"$LATEST\",\r ...", - "ingestionTime": 1559763018353 - }, - { - "timestamp": 1559763003173, - "message": "2019-06-05T19:30:03.173Z\t4ce9340a-b765-490f-ad8a-02ab3415e2bf\tINFO\tEVENT\r{\r \"key\": \"value\"\r}\n", - "ingestionTime": 1559763018353 - }, - { - "timestamp": 1559763003218, - "message": "END RequestId: 4ce9340a-b765-490f-ad8a-02ab3415e2bf\n", - "ingestionTime": 1559763018353 - }, - { - "timestamp": 1559763003218, - "message": "REPORT RequestId: 4ce9340a-b765-490f-ad8a-02ab3415e2bf\tDuration: 26.73 ms\tBilled Duration: 100 ms \tMemory Size: 128 MB\tMax Memory Used: 75 MB\t\n", - "ingestionTime": 1559763018353 - } - ], - "nextForwardToken": "f/34783877304859518393868359594929986069206639495374241795", - "nextBackwardToken": "b/34783877303811383369537420289090800615709599058929582080" -} -``` - -## Deleting logs - -Log groups aren't deleted automatically when you delete a function\. To avoid storing logs indefinitely, delete the log group, or [configure a retention period](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Working-with-log-groups-and-streams.html#SettingLogRetention) after which logs are deleted automatically\. \ No newline at end of file diff --git a/doc_source/nodejs-package.md b/doc_source/nodejs-package.md deleted file mode 100644 index e06816ec..00000000 --- a/doc_source/nodejs-package.md +++ /dev/null @@ -1,100 +0,0 @@ -# AWS Lambda deployment package in Node\.js - -A deployment package is a ZIP archive that contains your function code and dependencies\. You need to create a deployment package if you use the Lambda API to manage functions, or if you need to include libraries and dependencies other than the AWS SDK\. You can upload the package directly to Lambda, or you can use an Amazon S3 bucket, and then upload it to Lambda\. If the deployment package is larger than 50 MB, you must use Amazon S3\. - -If you use the Lambda [console editor](code-editor.md) to author your function, the console manages the deployment package\. You can use this method as long as you don't need to add any libraries\. You can also use it to update a function that already has libraries in the deployment package, as long as the total size doesn't exceed 3 MB\. - -**Note** -To keep your deployment package size small, package your function's dependencies in layers\. Layers let you manage your dependencies independently, can be used by multiple functions, and can be shared with other accounts\. For details, see [AWS Lambda layers](configuration-layers.md)\. - -**Topics** -+ [Updating a function with no dependencies](#nodejs-package-codeonly) -+ [Updating a function with additional dependencies](#nodejs-package-dependencies) - -## Updating a function with no dependencies - -To update a function by using the Lambda API, use the [UpdateFunctionCode](API_UpdateFunctionCode.md) operation\. Create an archive that contains your function code, and upload it using the AWS CLI\. - -**To update a Node\.js function with no dependencies** - -1. Create a ZIP archive\. - - ``` - ~/my-function$ zip function.zip index.js - ``` - -1. Use the `update-function-code` command to upload the package\. - - ``` - ~/my-function$ aws lambda update-function-code --function-name my-function --zip-file fileb://function.zip - { - "FunctionName": "my-function", - "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function", - "Runtime": "nodejs12.x", - "Role": "arn:aws:iam::123456789012:role/lambda-role", - "Handler": "index.handler", - "CodeSha256": "Qf0hMc1I2di6YFMi9aXm3JtGTmcDbjniEuiYonYptAk=", - "Version": "$LATEST", - "TracingConfig": { - "Mode": "Active" - }, - "RevisionId": "983ed1e3-ca8e-434b-8dc1-7d72ebadd83d", - ... - } - ``` - -## Updating a function with additional dependencies - -If your function depends on libraries other than the SDK for JavaScript, install them to a local directory with [npm](https://www.npmjs.com/), and include them in your deployment package\. You can also include the SDK for JavaScript if you need a newer version than the one [included on the runtime](lambda-nodejs.md), or to ensure that the version doesn't change in the future\. - -**To update a Node\.js function with dependencies** - -1. Install libraries in the node\_modules directory with the `npm install` command\. - - ``` - ~/my-function$ npm install aws-xray-sdk - ``` - - This creates a folder structure that's similar to the following\. - - ``` - ~/my-function - ├── index.js - └── node_modules - ├── async - ├── async-listener - ├── atomic-batcher - ├── aws-sdk - ├── aws-xray-sdk - ├── aws-xray-sdk-core - ``` - -1. Create a ZIP file that contains the contents of your project folder\. - - ``` - ~/my-function$ zip -r function.zip . - ``` - -1. Use the `update-function-code` command to upload the package\. - - ``` - ~/my-function$ aws lambda update-function-code --function-name my-function --zip-file fileb://function.zip - { - "FunctionName": "my-function", - "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function", - "Runtime": "nodejs12.x", - "Role": "arn:aws:iam::123456789012:role/lambda-role", - "Handler": "index.handler", - "CodeSha256": "Qf0hMc1I2di6YFMi9aXm3JtGTmcDbjniEuiYonYptAk=", - "Version": "$LATEST", - "TracingConfig": { - "Mode": "Active" - }, - "RevisionId": "983ed1e3-ca8e-434b-8dc1-7d72ebadd83d", - ... - } - ``` - -In addition to code and libraries, your deployment package can also contain executable files and other resources\. For more information, see the following: -+ [Running executables in AWS Lambda](https://aws.amazon.com/blogs/compute/running-executables-in-aws-lambda/) -+ [Using packages and native nodejs modules in AWS Lambda ](https://aws.amazon.com/blogs/compute/nodejs-packages-in-lambda/) \ No newline at end of file diff --git a/doc_source/nodejs-tracing.md b/doc_source/nodejs-tracing.md deleted file mode 100644 index 51e4447e..00000000 --- a/doc_source/nodejs-tracing.md +++ /dev/null @@ -1,39 +0,0 @@ -# Instrumenting Node\.js code in AWS Lambda - -In Node\.js, you can have Lambda emit subsegments to X\-Ray to show you information about downstream calls to other AWS services made by your function\. To do so, you first need to include the [the AWS X\-Ray SDK for Node\.js](https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-nodejs.html) in your deployment package\. In addition, wrap your AWS SDK `require` statement in the following manner\. - -``` -const AWSXRay = require('aws-xray-sdk-core') -const AWS = AWSXRay.captureAWS(require('aws-sdk')) -``` - -Then, use the AWS variable defined in the preceding example to initialize any service client that you want to trace with X\-Ray, for example: - -``` -const s3 = new AWS.S3() -``` - -After following these steps, any call made from your function using `s3Client` results in an X\-Ray subsegment that represents that call\. As an example, you can run the Node\.js function following to see how the trace looks in X\-Ray\. - -**Example index\.js** - -``` -const AWSXRay = require('aws-xray-sdk-core') -const AWS = AWSXRay.captureAWS(require('aws-sdk')) -const s3 = new AWS.S3() - -exports.handler = async function(event) { - return s3.listBuckets().promise() -} -``` - -The following example shows a trace with 2 segments, both named **my\-function**\. - -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/nodejs-xray-timeline.png) - -The first segment represents the invocation request processed by the Lambda service\. The second segment records the work done by your function\. The function segment has 3 subsegments\. - -**** -+ **Initialization** – Represents time spent loading your function and running [initialization code](gettingstarted-features.md#gettingstarted-features-programmingmodel)\. This subsegment only appears for the first event processed by each instance of your function\. -+ **Invocation** – Represents the work done by your handler code\. By instrumenting your code, you can extend this subsegment with additional subsegments\. -+ **Overhead** – Represents the work done by the Lambda runtime to prepare to handle the next event\. \ No newline at end of file diff --git a/doc_source/permissions-boundary.md b/doc_source/permissions-boundary.md deleted file mode 100644 index 6b010ec3..00000000 --- a/doc_source/permissions-boundary.md +++ /dev/null @@ -1,60 +0,0 @@ -# Using permissions boundaries for AWS Lambda applications - -When you [create an application](applications-tutorial.md) in the AWS Lambda console, Lambda applies a *permissions boundary* to the application's IAM roles\. The permissions boundary limits the scope of the [execution role](lambda-intro-execution-role.md) that the application's template creates for each of its functions, and any roles that you add to the template\. The permissions boundary prevents users with write access to the application's Git repository from escalating the application's permissions beyond the scope of its own resources\. - -The application templates in the Lambda console include a global property that applies a permissions boundary to all functions that they create\. - -``` -Globals: - Function: - PermissionsBoundary: !Sub 'arn:${AWS::Partition}:iam::${AWS::AccountId}:policy/${AppId}-${AWS::Region}-PermissionsBoundary' -``` - -The boundary limits the permissions of the functions' roles\. You can add permissions to a function's execution role in the template, but that permission is only effective if it's also allowed by the permissions boundary\. The role that AWS CloudFormation assumes to deploy the application enforces the use of the permissions boundary\. That role only has permission to create and pass roles that have the application's permissions boundary attached\. - -By default, an application's permissions boundary enables functions to perform actions on the resources in the application\. For example, if the application includes an Amazon DynamoDB table, the boundary allows access to any API action that can be restricted to operate on specific tables with resource\-level permissions\. You can only use actions that don't support resource\-level permissions if they're specifically permitted in the boundary\. These include Amazon CloudWatch Logs and AWS X\-Ray API actions for logging and tracing\. - -**Example Permissions boundary** - -``` -{ - "Version": "2012-10-17", - "Statement": [ - { - "Action": [ - "*" - ], - "Resource": [ - "arn:aws:lambda:us-east-2:123456789012:function:my-app-getAllItemsFunction-*", - "arn:aws:lambda:us-east-2:123456789012:function:my-app-getByIdFunction-*", - "arn:aws:lambda:us-east-2:123456789012:function:my-app-putItemFunction-*", - "arn:aws:dynamodb:us-east-1:123456789012:table/my-app-SampleTable-*" - ], - "Effect": "Allow", - "Sid": "StackResources" - }, - { - "Action": [ - "logs:CreateLogGroup", - "logs:CreateLogStream", - "logs:DescribeLogGroups", - "logs:PutLogEvents", - "xray:Put*" - ], - "Resource": "*", - "Effect": "Allow", - "Sid": "StaticPermissions" - }, - ... - ] -} -``` - -To access other resources or API actions, you or an administrator must expand the permissions boundary to include those resources\. You might also need to update the execution role or deployment role of an application to allow the use of additional actions\. -+ **Permissions boundary** – Extend the application's permissions boundary when you add resources to your application, or the execution role needs access to more actions\. In IAM, add resources to the boundary to allow the use of API actions that support resource\-level permissions on that resource's type\. For actions that don't support resource\-level permissions, add them in a statement that isn't scoped to any resource\. -+ **Execution role** – Extend a function's execution role when it needs to use additional actions\. In the application template, add policies to the execution role\. The intersection of permissions in the boundary and execution role is granted to the function\. -+ **Deployment role** – Extend the application's deployment role when it needs additional permissions to create or configure resources\. In IAM, add policies to the application's deployment role\. The deployment role needs the same user permissions that you need to deploy or update an application in AWS CloudFormation\. - -For a tutorial that walks through adding resources to an application and extending its permissions, see [Creating an application with continuous delivery in the Lambda console](applications-tutorial.md)\. - -For more information, see [Permissions boundaries for IAM entities](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) in the IAM User Guide\. \ No newline at end of file diff --git a/doc_source/powershell-context.md b/doc_source/powershell-context.md deleted file mode 100644 index bbcc3dca..00000000 --- a/doc_source/powershell-context.md +++ /dev/null @@ -1,26 +0,0 @@ -# AWS Lambda context object in PowerShell - -When Lambda runs your function, it passes context information by making a `$LambdaContext` variable available to the [handler](powershell-handler.md)\. This variable provides methods and properties with information about the invocation, function, and execution environment\. - -**Context properties** -+ `FunctionName` – The name of the Lambda function\. -+ `FunctionVersion` – The [version](configuration-versions.md) of the function\. -+ `InvokedFunctionArn` – The Amazon Resource Name \(ARN\) that's used to invoke the function\. Indicates if the invoker specified a version number or alias\. -+ `MemoryLimitInMB` – The amount of memory that's allocated for the function\. -+ `AwsRequestId` – The identifier of the invocation request\. -+ `LogGroupName` – The log group for the function\. -+ `LogStreamName` – The log stream for the function instance\. -+ `RemainingTime` – The number of milliseconds left before the execution times out\. -+ `Identity` – \(mobile apps\) Information about the Amazon Cognito identity that authorized the request\. -+ `ClientContext` – \(mobile apps\) Client context that's provided to Lambda by the client application\. -+ `Logger` – The [logger object](powershell-logging.md) for the function\. - -The following PowerShell code snippet shows a simple handler function that prints some of the context information\. - -``` -#Requires -Modules @{ModuleName='AWSPowerShell.NetCore';ModuleVersion='3.3.618.0'} -Write-Host 'Function name:' $LambdaContext.FunctionName -Write-Host 'Remaining milliseconds:' $LambdaContext.RemainingTime.TotalMilliseconds -Write-Host 'Log group name:' $LambdaContext.LogGroupName -Write-Host 'Log stream name:' $LambdaContext.LogStreamName -``` \ No newline at end of file diff --git a/doc_source/powershell-devenv.md b/doc_source/powershell-devenv.md deleted file mode 100644 index 54b84ff7..00000000 --- a/doc_source/powershell-devenv.md +++ /dev/null @@ -1,15 +0,0 @@ -# Setting Up a PowerShell Development Environment - -To set up your development environment for writing PowerShell scripts, do the following: - -1. **Install the correct version of PowerShell** – Lambda's support for PowerShell is based on the cross\-platform PowerShell Core 6\.0 release\. This means that you can develop your PowerShell Lambda functions on Windows, Linux, or Mac\. If you don’t have this version of PowerShell installed, you can find instructions in [Installing PowerShell Core](https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell#powershell-core)\. - -1. **Install the \.NET Core 3\.1 SDK** – Because PowerShell Core is built on top of \.NET Core, the Lambda support for PowerShell uses the same \.NET Core 3\.1 Lambda runtime for both \.NET Core and PowerShell Lambda functions\. The \.NET Core 3\.1 SDK is used by the new Lambda PowerShell publishing cmdlets to create the Lambda deployment package\. The \.NET Core 3\.1 SDK is available at [\.NET downloads](https://www.microsoft.com/net/download) on the Microsoft website\. Be sure to install the SDK and not the runtime installation\. - -1. **Install the AWSLambdaPSCore module** – You can install this either from the [ PowerShell Gallery](https://www.powershellgallery.com/packages/AWSLambdaPSCore), or you can install it by using the following PowerShell Core shell command: - - ``` - Install-Module AWSLambdaPSCore -Scope CurrentUser - ``` - -1. **\(Optional\) Install AWS Tools for PowerShell** – You can install either the modularized [AWS\.Tools](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-welcome.html#pwsh_structure_pstools) or single\-module [AWSPowerShell\.NetCore](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-welcome.html#pwsh_structure_pscore) version in PowerShell Core 6\.0 to use the Lambda API within your PowerShell environment\\\. For instructions, see [Installing the AWS Tools for PowerShell](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-getting-set-up.html) \ No newline at end of file diff --git a/doc_source/powershell-exceptions.md b/doc_source/powershell-exceptions.md deleted file mode 100644 index 1e1f8142..00000000 --- a/doc_source/powershell-exceptions.md +++ /dev/null @@ -1,50 +0,0 @@ -# AWS Lambda function errors in PowerShell - -If your Lambda function has a terminating error, AWS Lambda recognizes the failure, serializes the error information into JSON, and returns it\. - -Consider the following PowerShell script example statement: - -``` -throw 'The Account is not found' -``` - -When you invoke this Lambda function, it throws a terminating error, and AWS Lambda returns the following error message: - -``` -{ - "errorMessage": "The Account is not found", - "errorType": "RuntimeException" -} -``` - -Note the `errorType` is `RuntimeException`, which is the default exception thrown by PowerShell\. You can use custom error types by throwing the error like this: - -``` -throw @{'Exception'='AccountNotFound';'Message'='The Account is not found'} -``` - -The error message is serialized with `errorType` set to `AccountNotFound`: - -``` -{ - "errorMessage": "The Account is not found", - "errorType": "AccountNotFound" -} -``` - -If you don't need an error message, you can throw a string in the format of an error code\. The error code format requires that the string starts with a character and only contain letters and digits afterwards, with no spaces or symbols\. - -For example, if your Lambda function contains the following: - -``` -throw 'AccountNotFound' -``` - -The error is serialized like this: - -``` -{ - "errorMessage": "AccountNotFound", - "errorType": "AccountNotFound" -} -``` \ No newline at end of file diff --git a/doc_source/powershell-handler.md b/doc_source/powershell-handler.md deleted file mode 100644 index df76d38b..00000000 --- a/doc_source/powershell-handler.md +++ /dev/null @@ -1,32 +0,0 @@ -# AWS Lambda function handler in PowerShell - -When a Lambda function is invoked, the Lambda handler invokes the PowerShell script\. - -When the PowerShell script is invoked, the following variables are predefined: -+ *$LambdaInput* – A PSObject that contains the input to the handler\. This input can be event data \(published by an event source\) or custom input that you provide, such as a string or any custom data object\. -+ *$LambdaContext* – An Amazon\.Lambda\.Core\.ILambdaContext object that you can use to access information about the current execution—such as the name of the current function, the memory limit, execution time remaining, and logging\. - -For example, consider the following PowerShell example code\. - -``` -#Requires -Modules @{ModuleName='AWSPowerShell.NetCore';ModuleVersion='3.3.618.0'} -Write-Host 'Function Name:' $LambdaContext.FunctionName -``` - -This script returns the FunctionName property that's obtained from the $LambdaContext variable\. - -**Note** -You're required to use the `#Requires` statement within your PowerShell scripts to indicate the modules that your scripts depend on\. This statement performs two important tasks\. 1\) It communicates to other developers which modules the script uses, and 2\) it identifies the dependent modules that AWS PowerShell tools need to package with the script, as part of the deployment\. For more information about the `#Requires` statement in PowerShell, see [ About requires](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_requires?view=powershell-6)\. For more information about PowerShell deployment packages, see [AWS Lambda deployment package in PowerShell](powershell-package.md)\. -When your PowerShell Lambda function uses the AWS PowerShell cmdlets, be sure to set a `#Requires` statement that references the `AWSPowerShell.NetCore` module, which supports PowerShell Core—and not the `AWSPowerShell` module, which only supports Windows PowerShell\. Also, be sure to use version 3\.3\.270\.0 or newer of `AWSPowerShell.NetCore` which optimizes the cmdlet import process\. If you use an older version, you'll experience longer cold starts\. For more information, see [ AWS Tools for PowerShell](https://aws.amazon.com/documentation/powershell/?id=docs_gateway)\. - -## Returning data - -Some Lambda invocations are meant to return data back to their caller\. For example, if an invocation was in response to a web request coming from API Gateway, then our Lambda function needs to return back the response\. For PowerShell Lambda, the last object that's added to the PowerShell pipeline is the return data from the Lambda invocation\. If the object is a string, the data is returned as is\. Otherwise the object is converted to JSON by using the `ConvertTo-Json` cmdlet\. - -For example, consider the following PowerShell statement, which adds `$PSVersionTable` to the PowerShell pipeline: - -``` -$PSVersionTable -``` - -After the PowerShell script is finished, the last object in the PowerShell pipeline is the return data for the Lambda function\. `$PSVersionTable` is a PowerShell global variable that also provides information about the running environment\. \ No newline at end of file diff --git a/doc_source/powershell-logging.md b/doc_source/powershell-logging.md deleted file mode 100644 index 182bd906..00000000 --- a/doc_source/powershell-logging.md +++ /dev/null @@ -1,170 +0,0 @@ -# AWS Lambda function logging in PowerShell - -Your Lambda function comes with a CloudWatch Logs log group, with a log stream for each instance of your function\. The runtime sends details about each invocation to the log stream, and relays logs and other output from your function's code\. - -To output logs from your function code, you can use cmdlets on [Microsoft\.PowerShell\.Utility ](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility), or any logging module that writes to `stdout` or `stderr`\. The following example uses `Write-Host`\. - -**Example [function/Handler\.ps1](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/blank-powershell/function/Handler.ps1) – Logging** - -``` -#Requires -Modules @{ModuleName='AWSPowerShell.NetCore';ModuleVersion='3.3.618.0'} -Write-Host `## Environment variables -Write-Host AWS_LAMBDA_FUNCTION_VERSION=$Env:AWS_LAMBDA_FUNCTION_VERSION -Write-Host AWS_LAMBDA_LOG_GROUP_NAME=$Env:AWS_LAMBDA_LOG_GROUP_NAME -Write-Host AWS_LAMBDA_LOG_STREAM_NAME=$Env:AWS_LAMBDA_LOG_STREAM_NAME -Write-Host AWS_EXECUTION_ENV=$Env:AWS_EXECUTION_ENV -Write-Host AWS_LAMBDA_FUNCTION_NAME=$Env:AWS_LAMBDA_FUNCTION_NAME -Write-Host PATH=$Env:PATH -Write-Host `## Event -Write-Host (ConvertTo-Json -InputObject $LambdaInput -Compress -Depth 3) -``` - -**Example Log format** - -``` -START RequestId: 56639408-xmpl-435f-9041-ac47ae25ceed Version: $LATEST -Importing module ./Modules/AWSPowerShell.NetCore/3.3.618.0/AWSPowerShell.NetCore.psd1 -[Information] - ## Environment variables -[Information] - AWS_LAMBDA_FUNCTION_VERSION=$LATEST -[Information] - AWS_LAMBDA_LOG_GROUP_NAME=/aws/lambda/blank-powershell-function-18CIXMPLHFAJJ -[Information] - AWS_LAMBDA_LOG_STREAM_NAME=2020/04/01/[$LATEST]53c5xmpl52d64ed3a744724d9c201089 -[Information] - AWS_EXECUTION_ENV=AWS_Lambda_dotnetcore2.1_powershell_1.0.0 -[Information] - AWS_LAMBDA_FUNCTION_NAME=blank-powershell-function-18CIXMPLHFAJJ -[Information] - PATH=/var/lang/bin:/usr/local/bin:/usr/bin/:/bin:/opt/bin -[Information] - ## Event -[Information] - -{ - "Records": [ - { - "messageId": "19dd0b57-b21e-4ac1-bd88-01bbb068cb78", - "receiptHandle": "MessageReceiptHandle", - "body": "Hello from SQS!", - "attributes": { - "ApproximateReceiveCount": "1", - "SentTimestamp": "1523232000000", - "SenderId": "123456789012", - "ApproximateFirstReceiveTimestamp": "1523232000001" - }, - ... -END RequestId: 56639408-xmpl-435f-9041-ac47ae25ceed -REPORT RequestId: 56639408-xmpl-435f-9041-ac47ae25ceed Duration: 3906.38 ms Billed Duration: 4000 ms Memory Size: 512 MB Max Memory Used: 367 MB Init Duration: 5960.19 ms -XRAY TraceId: 1-5e843da6-733cxmple7d0c3c020510040 SegmentId: 3913xmpl20999446 Sampled: true -``` - -The \.NET runtime logs the `START`, `END`, and `REPORT` lines for each invocation\. The report line provides the following details\. - -**Report Log** -+ **RequestId** – The unique request ID for the invocation\. -+ **Duration** – The amount of time that your function's handler method spent processing the event\. -+ **Billed Duration** – The amount of time billed for the invocation\. -+ **Memory Size** – The amount of memory allocated to the function\. -+ **Max Memory Used** – The amount of memory used by the function\. -+ **Init Duration** – For the first request served, the amount of time it took the runtime to load the function and run code outside of the handler method\. -+ **XRAY TraceId** – For traced requests, the [AWS X\-Ray trace ID](lambda-x-ray.md)\. -+ **SegmentId** – For traced requests, the X\-Ray segment ID\. -+ **Sampled** – For traced requests, the sampling result\. - -You can view logs in the Lambda console, in the CloudWatch Logs console, or from the command line\. - -**Topics** -+ [Viewing logs in the AWS Management Console](#powershell-logging-console) -+ [Using the AWS CLI](#powershell-logging-cli) -+ [Deleting logs](#powershell-logging-delete) - -## Viewing logs in the AWS Management Console - -The Lambda console shows log output when you test a function on the function configuration page\. To view logs for all invocations, use the CloudWatch Logs console\. - -**To view your Lambda function's logs** - -1. Open the [Logs page of the CloudWatch console](https://console.aws.amazon.com/cloudwatch/home?#logs:)\. - -1. Choose the log group for your function \(**/aws/lambda/*function\-name***\)\. - -1. Choose the first stream in the list\. - -Each log stream corresponds to an [instance of your function](runtimes-context.md)\. New streams appear when you update your function and when additional instances are created to handle multiple concurrent invocations\. To find logs for specific invocations, you can instrument your function with X\-Ray, and record details about the request and log stream in the trace\. For a sample application that correlates logs and traces with X\-Ray, see [Error processor sample application for AWS Lambda](samples-errorprocessor.md)\. - -## Using the AWS CLI - -To get logs for an invocation from the command line, use the `--log-type` option\. The response includes a `LogResult` field that contains up to 4 KB of base64\-encoded logs from the invocation\. - -``` -$ aws lambda invoke --function-name my-function out --log-type Tail -{ - "StatusCode": 200, - "LogResult": "U1RBUlQgUmVxdWVzdElkOiA4N2QwNDRiOC1mMTU0LTExZTgtOGNkYS0yOTc0YzVlNGZiMjEgVmVyc2lvb...", - "ExecutedVersion": "$LATEST" -} -``` - -You can use the `base64` utility to decode the logs\. - -``` -$ aws lambda invoke --function-name my-function out --log-type Tail \ ---query 'LogResult' --output text | base64 -d -START RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 Version: $LATEST - "AWS_SESSION_TOKEN": "AgoJb3JpZ2luX2VjELj...", "_X_AMZN_TRACE_ID": "Root=1-5d02e5ca-f5792818b6fe8368e5b51d50;Parent=191db58857df8395;Sampled=0"",ask/lib:/opt/lib", -END RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 -REPORT RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 Duration: 79.67 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 73 MB -``` - -The `base64` utility is available on Linux, macOS, and [Ubuntu on Windows](https://docs.microsoft.com/en-us/windows/wsl/install-win10)\. For macOS, the command is `base64 -D`\. - -To get full log events from the command line, you can include the log stream name in the output of your function, as shown in the preceding example\. The following example script invokes a function named `my-function` and downloads the last five log events\. - -**Example get\-logs\.sh Script** -This example requires that `my-function` returns a log stream ID\. - -``` -#!/bin/bash -aws lambda invoke --function-name my-function --payload '{"key": "value"}' out -sed -i'' -e 's/"//g' out -sleep 15 -aws logs get-log-events --log-group-name /aws/lambda/my-function --log-stream-name $(cat out) --limit 5 -``` - -The script uses `sed` to remove quotes from the output file, and sleeps for 15 seconds to allow time for the logs to be available\. The output includes the response from Lambda and the output from the `get-log-events` command\. - -``` -$ ./get-logs.sh -{ - "StatusCode": 200, - "ExecutedVersion": "$LATEST" -} -{ - "events": [ - { - "timestamp": 1559763003171, - "message": "START RequestId: 4ce9340a-b765-490f-ad8a-02ab3415e2bf Version: $LATEST\n", - "ingestionTime": 1559763003309 - }, - { - "timestamp": 1559763003173, - "message": "2019-06-05T19:30:03.173Z\t4ce9340a-b765-490f-ad8a-02ab3415e2bf\tINFO\tENVIRONMENT VARIABLES\r{\r \"AWS_LAMBDA_FUNCTION_VERSION\": \"$LATEST\",\r ...", - "ingestionTime": 1559763018353 - }, - { - "timestamp": 1559763003173, - "message": "2019-06-05T19:30:03.173Z\t4ce9340a-b765-490f-ad8a-02ab3415e2bf\tINFO\tEVENT\r{\r \"key\": \"value\"\r}\n", - "ingestionTime": 1559763018353 - }, - { - "timestamp": 1559763003218, - "message": "END RequestId: 4ce9340a-b765-490f-ad8a-02ab3415e2bf\n", - "ingestionTime": 1559763018353 - }, - { - "timestamp": 1559763003218, - "message": "REPORT RequestId: 4ce9340a-b765-490f-ad8a-02ab3415e2bf\tDuration: 26.73 ms\tBilled Duration: 100 ms \tMemory Size: 128 MB\tMax Memory Used: 75 MB\t\n", - "ingestionTime": 1559763018353 - } - ], - "nextForwardToken": "f/34783877304859518393868359594929986069206639495374241795", - "nextBackwardToken": "b/34783877303811383369537420289090800615709599058929582080" -} -``` - -## Deleting logs - -Log groups aren't deleted automatically when you delete a function\. To avoid storing logs indefinitely, delete the log group, or [configure a retention period](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Working-with-log-groups-and-streams.html#SettingLogRetention) after which logs are deleted automatically\. \ No newline at end of file diff --git a/doc_source/powershell-package.md b/doc_source/powershell-package.md deleted file mode 100644 index 91eb31fb..00000000 --- a/doc_source/powershell-package.md +++ /dev/null @@ -1,80 +0,0 @@ -# AWS Lambda deployment package in PowerShell - -A PowerShell Lambda deployment package is a ZIP file that contains your PowerShell script, PowerShell modules that are required for your PowerShell script, and the assemblies needed to host PowerShell Core\. - -The AWSLambdaPSCore module has the following new cmdlets to help author and publish PowerShell Lambda functions\. - -**AWSLambdaPSCore cmdlets** -+ **Get\-AWSPowerShellLambdaTemplate** – Returns a list of getting started templates\. -+ **New\-AWSPowerShellLambda** – Creates an initial PowerShell script based on a template\. -+ **Publish\-AWSPowerShellLambda** – Publishes a given PowerShell script to Lambda\. -+ **New\-AWSPowerShellLambdaPackage** – Creates a Lambda deployment package that can be used in a CI/CD system for deployment\. - -To help get started writing and invoking a PowerShell script with Lambda, you can use the `New-AWSPowerShellLambda` cmdlet to create a starter script based on a template\. You can use the `Publish-AWSPowerShellLambda` cmdlet to deploy your script to AWS Lambda\. Then you can test your script either through the command line or the console\. - -To create a new PowerShell script, upload it, and test it, follow this procedure: - -1. Run the following command to view the list of available templates: - - ``` - PS C:\> Get-AWSPowerShellLambdaTemplate - - Template Description - -------- ----------- - Basic Bare bones script - CodeCommitTrigger Script to process AWS CodeCommit Triggers - ... - ``` - -1. Run the following command to create a sample script based on the `Basic` template: - - ``` - New-AWSPowerShellLambda -ScriptName MyFirstPSScript -Template Basic - ``` - - A new file named `MyFirstPSScript.ps1` is created in a new subdirectory of the current directory\. The name of the directory is based on the `-ScriptName` parameter\. You can use the `-Directory` parameter to choose an alternative directory\. - - You can see that the new file has the following contents: - - ``` - # PowerShell script file to be executed as a AWS Lambda function. - # - # When executing in Lambda the following variables will be predefined. - # $LambdaInput - A PSObject that contains the Lambda function input data. - # $LambdaContext - An Amazon.Lambda.Core.ILambdaContext object that contains information about the currently running Lambda environment. - # - # The last item in the PowerShell pipeline will be returned as the result of the Lambda function. - # - # To include PowerShell modules with your Lambda function, like the AWSPowerShell.NetCore module, add a "#Requires" statement - # indicating the module and version. - - #Requires -Modules @{ModuleName='AWSPowerShell.NetCore';ModuleVersion='3.3.618.0'} - - # Uncomment to send the input to CloudWatch Logs - # Write-Host (ConvertTo-Json -InputObject $LambdaInput -Compress -Depth 5) - ``` - -1. To see how log messages from your PowerShell script are sent to CloudWatch Logs, uncomment the `Write-Host` line of the sample script\. - - To demonstrate how you can return data back from your Lambda functions, add a new line at the end of the script with `$PSVersionTable`\. This adds the `$PSVersionTable` to the PowerShell pipeline\. After the PowerShell script is complete, the last object in the PowerShell pipeline is the return data for the Lambda function\. `$PSVersionTable` is a PowerShell global variable that also provides information about the running environment\. - - After making these changes, the last two lines of the sample script look like this: - - ``` - Write-Host (ConvertTo-Json -InputObject $LambdaInput -Compress -Depth 5) - $PSVersionTable - ``` - -1. After editing the `MyFirstPSScript.ps1` file, change the directory to the script's location\. Then run the following command to publish the script to AWS Lambda: - - ``` - Publish-AWSPowerShellLambda -ScriptPath .\MyFirstPSScript.ps1 -Name MyFirstPSScript -Region us-east-2 - ``` - - Note that the `-Name` parameter specifies the Lambda function name, which appears in the Lambda console\. You can use this function to invoke your script manually\. - -1. Invoke your function with the AWS CLI `invoke` command\. - - ``` - > aws lambda invoke --function-name MyFirstPSScript out - ``` \ No newline at end of file diff --git a/doc_source/python-context.md b/doc_source/python-context.md deleted file mode 100644 index e7c2d459..00000000 --- a/doc_source/python-context.md +++ /dev/null @@ -1,44 +0,0 @@ -# AWS Lambda context object in Python - -When Lambda runs your function, it passes a context object to the [handler](python-handler.md)\. This object provides methods and properties that provide information about the invocation, function, and execution environment\. - -**Context methods** -+ `get_remaining_time_in_millis` – Returns the number of milliseconds left before the execution times out\. - -**Context properties** -+ `function_name` – The name of the Lambda function\. -+ `function_version` – The [version](configuration-versions.md) of the function\. -+ `invoked_function_arn` – The Amazon Resource Name \(ARN\) that's used to invoke the function\. Indicates if the invoker specified a version number or alias\. -+ `memory_limit_in_mb` – The amount of memory that's allocated for the function\. -+ `aws_request_id` – The identifier of the invocation request\. -+ `log_group_name` – The log group for the function\. -+ `log_stream_name` – The log stream for the function instance\. -+ `identity` – \(mobile apps\) Information about the Amazon Cognito identity that authorized the request\. - + `cognito_identity_id` – The authenticated Amazon Cognito identity\. - + `cognito_identity_pool_id` – The Amazon Cognito identity pool that authorized the invocation\. -+ `client_context` – \(mobile apps\) Client context that's provided to Lambda by the client application\. - + `client.installation_id` - + `client.app_title` - + `client.app_version_name` - + `client.app_version_code` - + `client.app_package_name` - + `custom` – A `dict` of custom values set by the mobile client application\. - + `env` – A `dict` of environment information provided by the AWS SDK\. - -The following example shows a handler function that logs context information\. - -**Example handler\.py** - -``` -import time -def get_my_log_stream(event, context):     - print("Log stream name:", context.log_stream_name) -   print("Log group name:", context.log_group_name) -   print("Request ID:",context.aws_request_id) -   print("Mem. limits(MB):", context.memory_limit_in_mb) - # Code will execute quickly, so we add a 1 second intentional delay so you can see that in time remaining value. - time.sleep(1) -   print("Time remaining (MS):", context.get_remaining_time_in_millis()) -``` - -In addition to the options listed above, you can also use the AWS X\-Ray SDK for [Instrumenting Python code in AWS Lambda](python-tracing.md) to identify critical code paths, trace their performance and capture the data for analysis\. \ No newline at end of file diff --git a/doc_source/python-exceptions.md b/doc_source/python-exceptions.md deleted file mode 100644 index 7e71b0ac..00000000 --- a/doc_source/python-exceptions.md +++ /dev/null @@ -1,56 +0,0 @@ -# AWS Lambda function errors in Python - -When your code raises an error, Lambda generates a JSON representation of the error\. This error document appears in the invocation log and, for synchronous invocations, in the output\. - -**Example lambda\_function\.py file – Exception** - -``` -def lambda_handler(event, context): - return x + 10 -``` - -This code results in a name error\. Lambda catches the error and generates a JSON document with fields for the error message, the type, and the stack trace\. - -``` -{ - "errorMessage": "name 'x' is not defined", - "errorType": "NameError", - "stackTrace": [ - " File \"/var/task/error_function.py\", line 2, in lambda_handler\n return x + 10\n" - ] -} -``` - -When you invoke the function from the command line, the AWS CLI splits the response into two documents\. To indicate that a function error occurred, the response displayed in the terminal includes a `FunctionError` field\. The response or error returned by the function is written to the output file\. - -``` -$ aws lambda invoke --function-name my-function out.json -{ - "StatusCode": 200, - "FunctionError": "Unhandled", - "ExecutedVersion": "$LATEST" -} -``` - -View the output file to see the error document\. - -``` -$ cat out.json -{"errorMessage": "name 'x' is not defined", "errorType": "NameError", "stackTrace": [" File \"/var/task/error_function.py\", line 2, in lambda_handler\n return x + 10\n"]} -``` - -**Note** -The 200 \(success\) status code in the response from Lambda indicates that there wasn't an error with the request that you sent to Lambda\. For issues that result in an error status code, see [Errors](API_Invoke.md#API_Invoke_Errors)\. - -Lambda also records up to 256 KB of the error object in the function's logs\. To view logs when you invoke the function from the command line, use the `--log-type` option and decode the base64 string in the response\. - -``` -$ aws lambda invoke --function-name my-function out.json --log-type Tail \ ---query 'LogResult' --output text | base64 -d -START RequestId: fc4f8810-88ff-4800-974c-12cec018a4b9 Version: $LATEST -     return x + 10/lambda_function.py", line 2, in lambda_handler -END RequestId: fc4f8810-88ff-4800-974c-12cec018a4b9 -REPORT RequestId: fc4f8810-88ff-4800-974c-12cec018a4b9 Duration: 12.33 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 56 MB -``` - -For more information about logs, see [AWS Lambda function logging in Python](python-logging.md)\. \ No newline at end of file diff --git a/doc_source/python-handler.md b/doc_source/python-handler.md deleted file mode 100644 index 36a36163..00000000 --- a/doc_source/python-handler.md +++ /dev/null @@ -1,33 +0,0 @@ -# AWS Lambda function handler in Python - -At the time you create a Lambda function, you specify a *handler*, which is a function in your code, that AWS Lambda can invoke when the service executes your code\. Use the following general syntax structure when creating a handler function in Python\. - -``` -def handler_name(event, context): - ... - return some_value -``` - -In the syntax, note the following: -+ `event` – AWS Lambda uses this parameter to pass in event data to the handler\. This parameter is usually of the Python `dict` type\. It can also be `list`, `str`, `int`, `float`, or `NoneType` type\. - - When you invoke your function, you determine the content and structure of the event\. When an AWS service invokes your function, the event structure varies by service\. For details, see [Using AWS Lambda with other services](lambda-services.md)\. -+ `context` – AWS Lambda uses this parameter to provide runtime information to your handler\. For details, see [AWS Lambda context object in Python](python-context.md)\. -+ Optionally, the handler can return a value\. What happens to the returned value depends on the invocation type you use when invoking the Lambda function: - + If you use the `RequestResponse` invocation type \(synchronous execution\), AWS Lambda returns the result of the Python function call to the client invoking the Lambda function \(in the HTTP response to the invocation request, serialized into JSON\)\. For example, AWS Lambda console uses the `RequestResponse` invocation type, so when you invoke the function using the console, the console will display the returned value\. - + If the handler returns objects that can't be serialized by `json.dumps`, the runtime returns an error\. - + If the handler returns `None`, as Python functions without a `return` statement implicitly do, the runtime returns `null`\. - + If you use the `Event` invocation type \(asynchronous execution\), the value is discarded\. - -For example, consider the following Python example code\. - -``` -def my_handler(event, context): - message = 'Hello {} {}!'.format(event['first_name'], - event['last_name']) -  return { - 'message' : message - } -``` - -This example has one function called `my_handler`\. The function returns a message containing data from the event it received as input\. \ No newline at end of file diff --git a/doc_source/python-logging.md b/doc_source/python-logging.md deleted file mode 100644 index 8d0abb3a..00000000 --- a/doc_source/python-logging.md +++ /dev/null @@ -1,185 +0,0 @@ -# AWS Lambda function logging in Python - -Your Lambda function comes with a CloudWatch Logs log group, with a log stream for each instance of your function\. The runtime sends details about each invocation to the log stream, and relays logs and other output from your function's code\. - -To output logs from your function code, you can use [the `print` method](https://docs.python.org/3/library/functions.html#print), or any logging library that writes to `stdout` or `stderr`\. The following example logs the values of environment variables and the event object\. - -**Example lambda\_function\.py** - -``` -import json -import os - -def lambda_handler(event, context): - print('## ENVIRONMENT VARIABLES') - print(os.environ) - print('## EVENT') - print(event) -``` - -**Example Log format** - -``` -START RequestId: 8f507cfc-xmpl-4697-b07a-ac58fc914c95 Version: $LATEST -## ENVIRONMENT VARIABLES -environ({'AWS_LAMBDA_LOG_GROUP_NAME': '/aws/lambda/my-function', 'AWS_LAMBDA_LOG_STREAM_NAME': '2020/01/31/[$LATEST]3893xmpl7fac4485b47bb75b671a283c', 'AWS_LAMBDA_FUNCTION_NAME': 'my-function', ...}) -## EVENT -{'key': 'value'} -END RequestId: 8f507cfc-xmpl-4697-b07a-ac58fc914c95 -REPORT RequestId: 8f507cfc-xmpl-4697-b07a-ac58fc914c95 Duration: 15.74 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 56 MB Init Duration: 130.49 ms -XRAY TraceId: 1-5e34a614-10bdxmplf1fb44f07bc535a1 SegmentId: 07f5xmpl2d1f6f85 Sampled: true -``` - -The Python runtime logs the `START`, `END`, and `REPORT` lines for each invocation\. The report line provides the following details\. - -**Report Log** -+ **RequestId** – The unique request ID for the invocation\. -+ **Duration** – The amount of time that your function's handler method spent processing the event\. -+ **Billed Duration** – The amount of time billed for the invocation\. -+ **Memory Size** – The amount of memory allocated to the function\. -+ **Max Memory Used** – The amount of memory used by the function\. -+ **Init Duration** – For the first request served, the amount of time it took the runtime to load the function and run code outside of the handler method\. -+ **XRAY TraceId** – For traced requests, the [AWS X\-Ray trace ID](lambda-x-ray.md)\. -+ **SegmentId** – For traced requests, the X\-Ray segment ID\. -+ **Sampled** – For traced requests, the sampling result\. - -You can view logs in the Lambda console, in the CloudWatch Logs console, or from the command line\. - -**Topics** -+ [Viewing logs in the AWS Management Console](#python-logging-console) -+ [Using the AWS CLI](#python-logging-cli) -+ [Deleting logs](#python-logging-delete) -+ [Logging library](#python-logging-lib) - -## Viewing logs in the AWS Management Console - -The Lambda console shows log output when you test a function on the function configuration page\. To view logs for all invocations, use the CloudWatch Logs console\. - -**To view your Lambda function's logs** - -1. Open the [Logs page of the CloudWatch console](https://console.aws.amazon.com/cloudwatch/home?#logs:)\. - -1. Choose the log group for your function \(**/aws/lambda/*function\-name***\)\. - -1. Choose the first stream in the list\. - -Each log stream corresponds to an [instance of your function](runtimes-context.md)\. New streams appear when you update your function and when additional instances are created to handle multiple concurrent invocations\. To find logs for specific invocations, you can instrument your function with X\-Ray, and record details about the request and log stream in the trace\. For a sample application that correlates logs and traces with X\-Ray, see [Error processor sample application for AWS Lambda](samples-errorprocessor.md)\. - -## Using the AWS CLI - -To get logs for an invocation from the command line, use the `--log-type` option\. The response includes a `LogResult` field that contains up to 4 KB of base64\-encoded logs from the invocation\. - -``` -$ aws lambda invoke --function-name my-function out --log-type Tail -{ - "StatusCode": 200, - "LogResult": "U1RBUlQgUmVxdWVzdElkOiA4N2QwNDRiOC1mMTU0LTExZTgtOGNkYS0yOTc0YzVlNGZiMjEgVmVyc2lvb...", - "ExecutedVersion": "$LATEST" -} -``` - -You can use the `base64` utility to decode the logs\. - -``` -$ aws lambda invoke --function-name my-function out --log-type Tail \ ---query 'LogResult' --output text | base64 -d -START RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 Version: $LATEST - "AWS_SESSION_TOKEN": "AgoJb3JpZ2luX2VjELj...", "_X_AMZN_TRACE_ID": "Root=1-5d02e5ca-f5792818b6fe8368e5b51d50;Parent=191db58857df8395;Sampled=0"",ask/lib:/opt/lib", -END RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 -REPORT RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 Duration: 79.67 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 73 MB -``` - -The `base64` utility is available on Linux, macOS, and [Ubuntu on Windows](https://docs.microsoft.com/en-us/windows/wsl/install-win10)\. For macOS, the command is `base64 -D`\. - -To get full log events from the command line, you can include the log stream name in the output of your function, as shown in the preceding example\. The following example script invokes a function named `my-function` and downloads the last five log events\. - -**Example get\-logs\.sh Script** -This example requires that `my-function` returns a log stream ID\. - -``` -#!/bin/bash -aws lambda invoke --function-name my-function --payload '{"key": "value"}' out -sed -i'' -e 's/"//g' out -sleep 15 -aws logs get-log-events --log-group-name /aws/lambda/my-function --log-stream-name $(cat out) --limit 5 -``` - -The script uses `sed` to remove quotes from the output file, and sleeps for 15 seconds to allow time for the logs to be available\. The output includes the response from Lambda and the output from the `get-log-events` command\. - -``` -$ ./get-logs.sh -{ - "StatusCode": 200, - "ExecutedVersion": "$LATEST" -} -{ - "events": [ - { - "timestamp": 1559763003171, - "message": "START RequestId: 4ce9340a-b765-490f-ad8a-02ab3415e2bf Version: $LATEST\n", - "ingestionTime": 1559763003309 - }, - { - "timestamp": 1559763003173, - "message": "2019-06-05T19:30:03.173Z\t4ce9340a-b765-490f-ad8a-02ab3415e2bf\tINFO\tENVIRONMENT VARIABLES\r{\r \"AWS_LAMBDA_FUNCTION_VERSION\": \"$LATEST\",\r ...", - "ingestionTime": 1559763018353 - }, - { - "timestamp": 1559763003173, - "message": "2019-06-05T19:30:03.173Z\t4ce9340a-b765-490f-ad8a-02ab3415e2bf\tINFO\tEVENT\r{\r \"key\": \"value\"\r}\n", - "ingestionTime": 1559763018353 - }, - { - "timestamp": 1559763003218, - "message": "END RequestId: 4ce9340a-b765-490f-ad8a-02ab3415e2bf\n", - "ingestionTime": 1559763018353 - }, - { - "timestamp": 1559763003218, - "message": "REPORT RequestId: 4ce9340a-b765-490f-ad8a-02ab3415e2bf\tDuration: 26.73 ms\tBilled Duration: 100 ms \tMemory Size: 128 MB\tMax Memory Used: 75 MB\t\n", - "ingestionTime": 1559763018353 - } - ], - "nextForwardToken": "f/34783877304859518393868359594929986069206639495374241795", - "nextBackwardToken": "b/34783877303811383369537420289090800615709599058929582080" -} -``` - -## Deleting logs - -Log groups aren't deleted automatically when you delete a function\. To avoid storing logs indefinitely, delete the log group, or [configure a retention period](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Working-with-log-groups-and-streams.html#SettingLogRetention) after which logs are deleted automatically\. - -## Logging library - -For more detailed logs, use the [logging library](https://docs.python.org/3/library/logging.html)\. - -``` -import json -import os -import logging -logger = logging.getLogger() -logger.setLevel(logging.INFO) - -def lambda_handler(event, context): - logger.info('## ENVIRONMENT VARIABLES') - logger.info(os.environ) - logger.info('## EVENT') - logger.info(event) -``` - -The output from `logger` includes the log level, timestamp, and request ID\. - -``` -START RequestId: 1c8df7d3-xmpl-46da-9778-518e6eca8125 Version: $LATEST -[INFO] 2020-01-31T22:12:58.534Z 1c8df7d3-xmpl-46da-9778-518e6eca8125 ## ENVIRONMENT VARIABLES - -[INFO] 2020-01-31T22:12:58.534Z 1c8df7d3-xmpl-46da-9778-518e6eca8125 environ({'AWS_LAMBDA_LOG_GROUP_NAME': '/aws/lambda/my-function', 'AWS_LAMBDA_LOG_STREAM_NAME': '2020/01/31/[$LATEST]1bbe51xmplb34a2788dbaa7433b0aa4d', 'AWS_LAMBDA_FUNCTION_NAME': 'my-function', ...}) - -[INFO] 2020-01-31T22:12:58.535Z 1c8df7d3-xmpl-46da-9778-518e6eca8125 ## EVENT - -[INFO] 2020-01-31T22:12:58.535Z 1c8df7d3-xmpl-46da-9778-518e6eca8125 {'key': 'value'} - -END RequestId: 1c8df7d3-xmpl-46da-9778-518e6eca8125 -REPORT RequestId: 1c8df7d3-xmpl-46da-9778-518e6eca8125 Duration: 2.75 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 56 MB Init Duration: 113.51 ms -XRAY TraceId: 1-5e34a66a-474xmpl7c2534a87870b4370 SegmentId: 073cxmpl3e442861 Sampled: true -``` \ No newline at end of file diff --git a/doc_source/python-package.md b/doc_source/python-package.md deleted file mode 100644 index 1c2033a3..00000000 --- a/doc_source/python-package.md +++ /dev/null @@ -1,209 +0,0 @@ -# AWS Lambda deployment package in Python - -A deployment package is a ZIP archive that contains your function code and dependencies\. You need to create a deployment package if you use the Lambda API to manage functions, or if you need to include libraries and dependencies other than the AWS SDK\. You can upload the package directly to Lambda, or you can use an Amazon S3 bucket, and then upload it to Lambda\. If the deployment package is larger than 50 MB, you must use Amazon S3\. - -If you use the Lambda [console editor](code-editor.md) to author your function, the console manages the deployment package\. You can use this method as long as you don't need to add any libraries\. You can also use it to update a function that already has libraries in the deployment package, as long as the total size doesn't exceed 3 MB\. - -**Note** -You can use the AWS SAM CLI `build` command to create a deployment package for your Python function code and dependencies\. The AWS SAM CLI also provides an option to build your deployment package inside a Docker image that is compatible with the Lambda execution environment\. See [Building applications with dependencies](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-using-build.html) in the AWS SAM Developer Guide for instructions\. - -**Topics** -+ [Prerequisites](#python-package-prereqs) -+ [Updating a function with no dependencies](#python-package-codeonly) -+ [Updating a function with additional dependencies](#python-package-dependencies) -+ [With a virtual environment](#python-package-venv) - -## Prerequisites - -These instructions assume that you already have a function\. If you haven't created a function yet, see [Building Lambda functions with Python](lambda-python.md)\. - -To follow the procedures in this guide, you will need a command line terminal or shell to run commands\. Commands are shown in listings preceded by a prompt symbol \($\) and the name of the current directory, when appropriate: - -``` -~/lambda-project$ this is a command -this is output -``` - -For long commands, an escape character \(`\`\) is used to split a command over multiple lines\. - -On Linux and macOS, use your preferred shell and package manager\. On Windows 10, you can [install the Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows\-integrated version of Ubuntu and Bash\. - -## Updating a function with no dependencies - -To create or update a function with the Lambda API, create an archive that contains your function code and upload it with the AWS CLI\. - -**To update a Python function with no dependencies** - -1. Create a ZIP archive\. - - ``` - ~/my-function$ zip function.zip lambda_function.py - adding: lambda_function.py (deflated 17%) - ``` - -1. Use the `update-function-code` command to upload the package\. - - ``` - ~/my-function$ aws lambda update-function-code --function-name my-function --zip-file fileb://function.zip - { - "FunctionName": "my-function", - "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function", - "Runtime": "python3.8", - "Role": "arn:aws:iam::123456789012:role/lambda-role", - "Handler": "lambda_function.lambda_handler", - "CodeSize": 815, - "CodeSha256": "GcZ05oeHoJi61VpQj7vCLPs8DwCXmX5sE/fE2IHsizc=", - "Version": "$LATEST", - "RevisionId": "d1e983e3-ca8e-434b-8dc1-7add83d72ebd", - ... - } - ``` - -## Updating a function with additional dependencies - -If your function depends on libraries other than the SDK for Python \(Boto 3\), install them to a local directory with [pip](https://pypi.org/project/pip/), and include them in your deployment package\. - -**Note** -For libraries that use extension modules written in C or C\+\+, build your deployment package in an Amazon Linux environment\. You can use the [SAM CLI build command](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-using-build.html), which uses Docker, or build your deployment package on Amazon EC2 or AWS CodeBuild\. - -The following example shows how to create a deployment package that includes a common graphics library named Pillow\. - -**To update a Python function with dependencies** - -1. Install libraries in a new, project\-local `package` directory with `pip`'s `--target` option\. - - ``` - ~/my-function$ pip install --target ./package Pillow - Collecting Pillow - Using cached https://files.pythonhosted.org/packages/62/8c/230204b8e968f6db00c765624f51cfd1ecb6aea57b25ba00b240ee3fb0bd/Pillow-5.3.0-cp37-cp37m-manylinux1_x86_64.whl - Installing collected packages: Pillow - Successfully installed Pillow-5.3.0 - ``` -**Note** -In order for `--target` to work on [Debian\-based systems](https://github.com/pypa/pip/issues/3826) like Ubuntu, you may also need to pass the `--system` flag to prevent `distutils` errors\. - -1. Create a ZIP archive of the dependencies\. - - ``` - ~/my-function$ cd package - ~/my-function/package$ zip -r9 ${OLDPWD}/function.zip . - adding: PIL/ (stored 0%) - adding: PIL/.libs/ (stored 0%) - adding: PIL/.libs/libfreetype-7ce95de6.so.6.16.1 (deflated 65%) - adding: PIL/.libs/libjpeg-3fe7dfc0.so.9.3.0 (deflated 72%) - adding: PIL/.libs/liblcms2-a6801db4.so.2.0.8 (deflated 67%) - ... - ``` - -1. Add your function code to the archive\. - - ``` - ~/my-function/package$ cd $OLDPWD - ~/my-function$ zip -g function.zip lambda_function.py - adding: lambda_function.py (deflated 56%) - ``` - -1. Update the function code\. - - ``` - ~/my-function$ aws lambda update-function-code --function-name my-function --zip-file fileb://function.zip - { - "FunctionName": "my-function", - "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function", - "Runtime": "python3.8", - "Role": "arn:aws:iam::123456789012:role/lambda-role", - "Handler": "lambda_function.lambda_handler", - "CodeSize": 2269409, - "CodeSha256": "GcZ05oeHoJi61VpQj7vCLPs8DwCXmX5sE/fE2IHsizc=", - "Version": "$LATEST", - "RevisionId": "a9c05ffd-8ad6-4d22-b6cd-d34a00c1702c", - ... - } - ``` - -## With a virtual environment - -In some cases, you may need to use a [virtual environment](https://virtualenv.pypa.io/en/latest/) to install dependencies for your function\. This can occur if your function or its dependencies have dependencies on native libraries, or if you used Homebrew to install Python\. - -**To update a Python function with a virtual environment** - -1. Create a virtual environment\. - - ``` - ~/my-function$ virtualenv v-env - Using base prefix '~/.local/python-3.7.0' - New python executable in v-env/bin/python3.8 - Also creating executable in v-env/bin/python - Installing setuptools, pip, wheel... - done. - ``` -**Note** -For Python 3\.3 and newer, you can use the built\-in [venv module](https://docs.python.org/3/library/venv.html) to create a virtual environment, instead of installing `virtualenv`\. - - ``` - ~/my-function$ python3 -m venv v-env - ``` - -1. Activate the environment\. - - ``` - ~/my-function$ source v-env/bin/activate - (v-env) ~/my-function$ - ``` - -1. Install libraries with pip\. - - ``` - (v-env) ~/my-function$ pip install Pillow - Collecting Pillow - Using cached https://files.pythonhosted.org/packages/62/8c/230204b8e968f6db00c765624f51cfd1ecb6aea57b25ba00b240ee3fb0bd/Pillow-5.3.0-cp37-cp37m-manylinux1_x86_64.whl - Installing collected packages: Pillow - Successfully installed Pillow-5.3.0 - ``` - -1. Deactivate the virtual environment\. - - ``` - (v-env) ~/my-function$ deactivate - ``` - -1. Create a ZIP archive with the contents of the library\. - - ``` - ~/my-function$ cd v-env/lib/python3.8/site-packages - ~/my-function/v-env/lib/python3.8/site-packages$ zip -r9 ${OLDPWD}/function.zip . - adding: easy_install.py (deflated 17%) - adding: PIL/ (stored 0%) - adding: PIL/.libs/ (stored 0%) - adding: PIL/.libs/libfreetype-7ce95de6.so.6.16.1 (deflated 65%) - adding: PIL/.libs/libjpeg-3fe7dfc0.so.9.3.0 (deflated 72%) - ... - ``` - - Depending on the library, dependencies may appear in either `site-packages` or `dist-packages`, and the first folder in the virtual environment may be `lib` or `lib64`\. You can use the `pip show` command to locate a specific package\. - -1. Add your function code to the archive\. - - ``` - ~/my-function/v-env/lib/python3.8/site-packages$ cd $OLDPWD - ~/my-function$ zip -g function.zip lambda_function.py - adding: lambda_function.py (deflated 56%) - ``` - -1. Update the function code\. - - ``` - ~/my-function$ aws lambda update-function-code --function-name my-function --zip-file fileb://function.zip - { - "FunctionName": "my-function", - "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function", - "Runtime": "python3.8", - "Role": "arn:aws:iam::123456789012:role/lambda-role", - "Handler": "lambda_function.lambda_handler", - "CodeSize": 5912988, - "CodeSha256": "A2P0NUWq1J+LtSbkuP8tm9uNYqs1TAa3M76ptmZCw5g=", - "Version": "$LATEST", - "RevisionId": "5afdc7dc-2fcb-4ca8-8f24-947939ca707f", - ... - } - ``` \ No newline at end of file diff --git a/doc_source/python-tracing.md b/doc_source/python-tracing.md deleted file mode 100644 index ee5a2fe8..00000000 --- a/doc_source/python-tracing.md +++ /dev/null @@ -1,68 +0,0 @@ -# Instrumenting Python code in AWS Lambda - -In Python, you can have Lambda emit subsegments to X\-Ray to show you information about downstream calls to other AWS services made by your function\. To do so, you first need to include the [the AWS X\-Ray SDK for Python](https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-python.html) in your deployment package\. In addition, you can patch the `boto3` \(or `botocore` if you are using sessions\), so any client you create to access other AWS services will automatically be traced by X\-Ray\. - -``` -import boto3 -from aws_xray_sdk.core import xray_recorder -from aws_xray_sdk.core import patch - -patch(['boto3']) -``` - -Once you've patched the module you are using to create clients, you can use it to create your traced clients, in the case below Amazon S3: - -``` -s3_client = boto3.client('s3') -``` - -The X\-Ray SDK for Python creates a subsegment for the call and records information from the request and response\. You can use the `aws_xray_sdk_sdk.core.xray_recorder` to create subsegments automatically by decorating your Lambda functions or manually by calling `xray_recorder.begin_subsegment()` and `xray_recorder.end_subsegment()` inside the function, as shown in the following Lambda function\. - -``` -import boto3 -from aws_xray_sdk.core import xray_recorder -from aws_xray_sdk.core import patch - -patch(['boto3']) - -s3_client = boto3.client('s3') - -def lambda_handler(event, context): - bucket_name = event['bucket_name'] - bucket_key = event['bucket_key'] - body = event['body'] - - put_object_into_s3(bucket_name, bucket_key, body) - get_object_from_s3(bucket_name, bucket_key) - -# Define subsegments manually -def put_object_into_s3(bucket_name, bucket_key, body): - try: - xray_recorder.begin_subsegment('put_object') - response = s3_client.put_object(Bucket=bucket_name, Key=bucket_key, Body=body) - status_code = response['ResponseMetadata']['HTTPStatusCode'] - xray_recorder.current_subsegment().put_annotation('put_response', status_code) - finally: - xray_recorder.end_subsegment() - -# Use decorators to automatically set the subsegments -@xray_recorder.capture('get_object') -def get_object_from_s3(bucket_name, bucket_key): - response = s3_client.get_object(Bucket=bucket_name, Key=bucket_key) - status_code = response['ResponseMetadata']['HTTPStatusCode'] - xray_recorder.current_subsegment().put_annotation('get_response', status_code) -``` - -**Note** -The X\-Ray SDK for Python allows you to patch the following modules: -botocore -boto3 -requests -sqlite3 -mysql -pymysql -You can use `patch_all()` to patch all of them at once\. - -Following is what a trace emitted by the code preceding looks like \(synchronous invocation\): - -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/AWS_X_Ray_Python.png) \ No newline at end of file diff --git a/doc_source/ruby-context.md b/doc_source/ruby-context.md deleted file mode 100644 index 33bd952b..00000000 --- a/doc_source/ruby-context.md +++ /dev/null @@ -1,18 +0,0 @@ -# AWS Lambda context object in Ruby - -When Lambda runs your function, it passes a context object to the [handler](ruby-handler.md)\. This object provides methods and properties that provide information about the invocation, function, and execution environment\. - -**Context methods** -+ `get_remaining_time_in_millis` – Returns the number of milliseconds left before the execution times out\. - -**Context properties** -+ `function_name` – The name of the Lambda function\. -+ `function_version` – The [version](configuration-versions.md) of the function\. -+ `invoked_function_arn` – The Amazon Resource Name \(ARN\) that's used to invoke the function\. Indicates if the invoker specified a version number or alias\. -+ `memory_limit_in_mb` – The amount of memory that's allocated for the function\. -+ `aws_request_id` – The identifier of the invocation request\. -+ `log_group_name` – The log group for the function\. -+ `log_stream_name` – The log stream for the function instance\. -+ `deadline_ms`– The date that the execution times out, in Unix time milliseconds\. -+ `identity` – \(mobile apps\) Information about the Amazon Cognito identity that authorized the request\. -+ `client_context`– \(mobile apps\) Client context that's provided to Lambda by the client application\. \ No newline at end of file diff --git a/doc_source/ruby-exceptions.md b/doc_source/ruby-exceptions.md deleted file mode 100644 index 1d1826e0..00000000 --- a/doc_source/ruby-exceptions.md +++ /dev/null @@ -1,71 +0,0 @@ -# AWS Lambda function errors in Ruby - -When your code raises an error, Lambda generates a JSON representation of the error\. This error document appears in the invocation log and, for synchronous invocations, in the output\. - -**Example function\.rb** - -``` -def handler(event:, context:) - puts "Processing event..." - [1, 2, 3].first("two") - "Success" -end -``` - -This code results in a type error\. Lambda catches the error and generates a JSON document with fields for the error message, the type, and the stack trace\. - -``` -{ - "errorMessage": "no implicit conversion of String into Integer", - "errorType": "Function", - "stackTrace": [ - "/var/task/function.rb:3:in `first'", - "/var/task/function.rb:3:in `handler'" - ] -} -``` - -When you invoke the function from the command line, the AWS CLI splits the response into two documents\. To indicate that a function error occurred, the response displayed in the terminal includes a `FunctionError` field\. The response or error returned by the function is written to the output file\. - -``` -$ aws lambda invoke --function-name my-function out.json -{ - "StatusCode": 200, - "FunctionError": "Unhandled", - "ExecutedVersion": "$LATEST" -} -``` - -View the output file to see the error document\. - -``` -$ cat out.json -{"errorMessage":"no implicit conversion of String into Integer","errorType":"Function","stackTrace":["/var/task/function.rb:3:in `first'","/var/task/function.rb:3:in `handler'"]} -``` - -**Note** -The 200 \(success\) status code in the response from Lambda indicates that there wasn't an error with the request that you sent to Lambda\. For issues that result in an error status code, see [Errors](API_Invoke.md#API_Invoke_Errors)\. - -Lambda also records up to 256 KB of the error object in the function's logs\. To view logs when you invoke the function from the command line, use the `--log-type` option and decode the base64 string in the response\. - -``` -$ aws lambda invoke --function-name my-function out.json --log-type Tail \ ---query 'LogResult' --output text | base64 -d -START RequestId: 5ce6a15a-f156-11e8-b8aa-25371a5ca2a3 Version: $LATEST -Processing event... -Error raised from handler method -{ - "errorMessage": "no implicit conversion of String into Integer", - "errorType": "Function", - "stackTrace": [ - "/var/task/function.rb:3:in `first'", - "/var/task/function.rb:3:in `handler'" - ] -} -END RequestId: 5ce6a15a-f156-11e8-b8aa-25371a5ca2a3 -REPORT RequestId: 5ce6a15a-f156-11e8-b8aa-25371a5ca2a3 Duration: 22.74 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 18 MB -``` - -For more information about logs, see [AWS Lambda function logging in Ruby](ruby-logging.md)\. - -Depending on the event source, AWS Lambda might retry the failed Lambda function\. For example, if Kinesis is the event source, AWS Lambda retries the failed invocation until the Lambda function succeeds or the records in the stream expire\. For more information on retries, see [Error handling and automatic retries in AWS Lambda](invocation-retries.md)\. \ No newline at end of file diff --git a/doc_source/ruby-handler.md b/doc_source/ruby-handler.md deleted file mode 100644 index ac53901f..00000000 --- a/doc_source/ruby-handler.md +++ /dev/null @@ -1,37 +0,0 @@ -# AWS Lambda function handler in Ruby - -Your Lambda function's handler is the method that Lambda calls when your function is invoked\. In the following example, the file `function.rb` defines a handler method named `handler`\. The handler function takes two objects as input and returns a JSON document\. - -**Example function\.rb** - -``` -require 'json' - -def handler(event:, context:) - { event: JSON.generate(event), context: JSON.generate(context.inspect) } -end -``` - -In your function configuration, the `handler` setting tells Lambda where to find the handler\. For the preceding example, the correct value for this setting is **function\.handler**\. It includes two names separated by a dot: the name of the file and the name of the handler method\. - -You can also define your handler method in a class\. The following example defines a handler method named `process` on a class named `Handler` in a module named `LambdaFunctions`\. - -**Example source\.rb** - -``` -module LambdaFunctions - class Handler - def self.process(event:,context:) - "Hello!" - end - end -end -``` - -In this case, the handler setting is **source\.LambdaFunctions::Handler\.process**\. - -The two objects that the handler accepts are the invocation event and context\. The event is a Ruby object that contains the payload that's provided by the invoker\. If the payload is a JSON document, the event object is a Ruby hash\. Otherwise, it's a string\. The [context object](ruby-context.md) has methods and properties that provide information about the invocation, the function, and the execution environment\. - -The function handler is executed every time your Lambda function is invoked\. Static code outside of the handler is executed once per instance of the function\. If your handler uses resources like SDK clients and database connections, you can create them outside of the handler method to reuse them for multiple invocations\. - -Each instance of your function can process multiple invocation events, but it only processes one event at a time\. The number of instances processing an event at any given time is your function's *concurrency*\. For more information about the Lambda execution context, see [AWS Lambda execution context](runtimes-context.md)\. \ No newline at end of file diff --git a/doc_source/ruby-logging.md b/doc_source/ruby-logging.md deleted file mode 100644 index f31ef2eb..00000000 --- a/doc_source/ruby-logging.md +++ /dev/null @@ -1,220 +0,0 @@ -# AWS Lambda function logging in Ruby - -Your Lambda function comes with a CloudWatch Logs log group, with a log stream for each instance of your function\. The runtime sends details about each invocation to the log stream, and relays logs and other output from your function's code\. - -To output logs from your function code, you can use `puts` statements, or any logging library that writes to `stdout` or `stderr`\. The following example logs the values of environment variables and the event object\. - -**Example lambda\_function\.rb** - -``` -# lambda_function.rb - -def handler(event:, context:) - puts "## ENVIRONMENT VARIABLES" - puts ENV.to_a - puts "## EVENT" - puts event.to_a -end -``` - -For more detailed logs, use the [logger library](https://ruby-doc.org/stdlib-2.7.0/libdoc/logger/rdoc/index.html)\. - -``` -# lambda_function.rb - -require 'logger' - -def handler(event:, context:) - logger = Logger.new($stdout) - logger.info('## ENVIRONMENT VARIABLES') - logger.info(ENV.to_a) - logger.info('## EVENT') - logger.info(event) - event.to_a -end -``` - -The output from `logger` includes the timestamp, process ID, log level, and request ID\. - -``` -I, [2019-10-26T10:04:01.689856 #8] INFO 6573a3a0-2fb1-4e78-a582-2c769282e0bd -- : ## EVENT -I, [2019-10-26T10:04:01.689874 #8] INFO 6573a3a0-2fb1-4e78-a582-2c769282e0bd -- : {"key1"=>"value1", "key2"=>"value2", "key3"=>"value3"} -``` - -The Lambda console shows log output when you test a function on the function configuration page\. To view logs for all invocations, use the CloudWatch Logs console\. - -**To view your Lambda function's logs** - -1. Open the [Logs page of the CloudWatch console](https://console.aws.amazon.com/cloudwatch/home?#logs:)\. - -1. Choose the log group for your function \(**/aws/lambda/*function\-name***\)\. - -1. Choose the first stream in the list\. - -Each log stream corresponds to an [instance of your function](runtimes-context.md)\. New streams appear when you update your function and when additional instances are created to handle multiple concurrent invocations\. To find logs for specific invocations, you can instrument your function with X\-Ray, and record details about the request and log stream in the trace\. For a sample application that correlates logs and traces with X\-Ray, see [Error processor sample application for AWS Lambda](samples-errorprocessor.md)\. - -To get logs for an invocation from the command line, use the `--log-type` option\. The response includes a `LogResult` field that contains up to 4 KB of base64\-encoded logs from the invocation\. - -``` -$ aws lambda invoke --function-name my-function out --log-type Tail -{ - "StatusCode": 200, - "LogResult": "U1RBUlQgUmVxdWVzdElkOiA4N2QwNDRiOC1mMTU0LTExZTgtOGNkYS0yOTc0YzVlNGZiMjEgVmVyc2lvb...", - "ExecutedVersion": "$LATEST" -} -``` - -You can use the `base64` utility to decode the logs\. - -``` -$ aws lambda invoke --function-name my-function out --log-type Tail \ ---query 'LogResult' --output text | base64 -d -START RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 Version: $LATEST - "AWS_SESSION_TOKEN": "AgoJb3JpZ2luX2VjELj...", "_X_AMZN_TRACE_ID": "Root=1-5d02e5ca-f5792818b6fe8368e5b51d50;Parent=191db58857df8395;Sampled=0"",ask/lib:/opt/lib", -END RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 -REPORT RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 Duration: 79.67 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 73 MB -``` - -The `base64` utility is available on Linux, macOS, and [Ubuntu on Windows](https://docs.microsoft.com/en-us/windows/wsl/install-win10)\. For macOS, the command is `base64 -D`\. - -Log groups aren't deleted automatically when you delete a function\. To avoid storing logs indefinitely, delete the log group, or [configure a retention period](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Working-with-log-groups-and-streams.html#SettingLogRetention) after which logs are deleted automatically\. - -**Example Log format** - -``` -START RequestId: 50aba555-99c8-4b21-8358-644ee996a05f Version: $LATEST -## ENVIRONMENT VARIABLES -AWS_LAMBDA_FUNCTION_VERSION -$LATEST -AWS_LAMBDA_LOG_GROUP_NAME -/aws/lambda/my-function -AWS_LAMBDA_LOG_STREAM_NAME -2020/01/31/[$LATEST]3f34xmpl069f4018b4a773bcfe8ed3f9 -AWS_EXECUTION_ENV -AWS_Lambda_ruby2.5 -... -## EVENT -key -value -END RequestId: 50aba555-xmpl-4b21-8358-644ee996a05f -REPORT RequestId: 50aba555-xmpl-4b21-8358-644ee996a05f Duration: 12.96 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 48 MB Init Duration: 117.86 ms -XRAY TraceId: 1-5e34a246-2a04xmpl0fa44eb60ea08c5f SegmentId: 454xmpl46ca1c7d3 Sampled: true -``` - -The Ruby runtime logs the `START`, `END`, and `REPORT` lines for each invocation\. The report line provides the following details\. - -**Report Log** -+ **RequestId** – The unique request ID for the invocation\. -+ **Duration** – The amount of time that your function's handler method spent processing the event\. -+ **Billed Duration** – The amount of time billed for the invocation\. -+ **Memory Size** – The amount of memory allocated to the function\. -+ **Max Memory Used** – The amount of memory used by the function\. -+ **Init Duration** – For the first request served, the amount of time it took the runtime to load the function and run code outside of the handler method\. -+ **XRAY TraceId** – For traced requests, the [AWS X\-Ray trace ID](lambda-x-ray.md)\. -+ **SegmentId** – For traced requests, the X\-Ray segment ID\. -+ **Sampled** – For traced requests, the sampling result\. - -You can view logs in the Lambda console, in the CloudWatch Logs console, or from the command line\. - -**Topics** -+ [Viewing logs in the AWS Management Console](#python-logging-console) -+ [Using the AWS CLI](#python-logging-cli) -+ [Deleting logs](#python-logging-delete) - -## Viewing logs in the AWS Management Console - -The Lambda console shows log output when you test a function on the function configuration page\. To view logs for all invocations, use the CloudWatch Logs console\. - -**To view your Lambda function's logs** - -1. Open the [Logs page of the CloudWatch console](https://console.aws.amazon.com/cloudwatch/home?#logs:)\. - -1. Choose the log group for your function \(**/aws/lambda/*function\-name***\)\. - -1. Choose the first stream in the list\. - -Each log stream corresponds to an [instance of your function](runtimes-context.md)\. New streams appear when you update your function and when additional instances are created to handle multiple concurrent invocations\. To find logs for specific invocations, you can instrument your function with X\-Ray, and record details about the request and log stream in the trace\. For a sample application that correlates logs and traces with X\-Ray, see [Error processor sample application for AWS Lambda](samples-errorprocessor.md)\. - -## Using the AWS CLI - -To get logs for an invocation from the command line, use the `--log-type` option\. The response includes a `LogResult` field that contains up to 4 KB of base64\-encoded logs from the invocation\. - -``` -$ aws lambda invoke --function-name my-function out --log-type Tail -{ - "StatusCode": 200, - "LogResult": "U1RBUlQgUmVxdWVzdElkOiA4N2QwNDRiOC1mMTU0LTExZTgtOGNkYS0yOTc0YzVlNGZiMjEgVmVyc2lvb...", - "ExecutedVersion": "$LATEST" -} -``` - -You can use the `base64` utility to decode the logs\. - -``` -$ aws lambda invoke --function-name my-function out --log-type Tail \ ---query 'LogResult' --output text | base64 -d -START RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 Version: $LATEST - "AWS_SESSION_TOKEN": "AgoJb3JpZ2luX2VjELj...", "_X_AMZN_TRACE_ID": "Root=1-5d02e5ca-f5792818b6fe8368e5b51d50;Parent=191db58857df8395;Sampled=0"",ask/lib:/opt/lib", -END RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 -REPORT RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 Duration: 79.67 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 73 MB -``` - -The `base64` utility is available on Linux, macOS, and [Ubuntu on Windows](https://docs.microsoft.com/en-us/windows/wsl/install-win10)\. For macOS, the command is `base64 -D`\. - -To get full log events from the command line, you can include the log stream name in the output of your function, as shown in the preceding example\. The following example script invokes a function named `my-function` and downloads the last five log events\. - -**Example get\-logs\.sh Script** -This example requires that `my-function` returns a log stream ID\. - -``` -#!/bin/bash -aws lambda invoke --function-name my-function --payload '{"key": "value"}' out -sed -i'' -e 's/"//g' out -sleep 15 -aws logs get-log-events --log-group-name /aws/lambda/my-function --log-stream-name $(cat out) --limit 5 -``` - -The script uses `sed` to remove quotes from the output file, and sleeps for 15 seconds to allow time for the logs to be available\. The output includes the response from Lambda and the output from the `get-log-events` command\. - -``` -$ ./get-logs.sh -{ - "StatusCode": 200, - "ExecutedVersion": "$LATEST" -} -{ - "events": [ - { - "timestamp": 1559763003171, - "message": "START RequestId: 4ce9340a-b765-490f-ad8a-02ab3415e2bf Version: $LATEST\n", - "ingestionTime": 1559763003309 - }, - { - "timestamp": 1559763003173, - "message": "2019-06-05T19:30:03.173Z\t4ce9340a-b765-490f-ad8a-02ab3415e2bf\tINFO\tENVIRONMENT VARIABLES\r{\r \"AWS_LAMBDA_FUNCTION_VERSION\": \"$LATEST\",\r ...", - "ingestionTime": 1559763018353 - }, - { - "timestamp": 1559763003173, - "message": "2019-06-05T19:30:03.173Z\t4ce9340a-b765-490f-ad8a-02ab3415e2bf\tINFO\tEVENT\r{\r \"key\": \"value\"\r}\n", - "ingestionTime": 1559763018353 - }, - { - "timestamp": 1559763003218, - "message": "END RequestId: 4ce9340a-b765-490f-ad8a-02ab3415e2bf\n", - "ingestionTime": 1559763018353 - }, - { - "timestamp": 1559763003218, - "message": "REPORT RequestId: 4ce9340a-b765-490f-ad8a-02ab3415e2bf\tDuration: 26.73 ms\tBilled Duration: 100 ms \tMemory Size: 128 MB\tMax Memory Used: 75 MB\t\n", - "ingestionTime": 1559763018353 - } - ], - "nextForwardToken": "f/34783877304859518393868359594929986069206639495374241795", - "nextBackwardToken": "b/34783877303811383369537420289090800615709599058929582080" -} -``` - -## Deleting logs - -Log groups aren't deleted automatically when you delete a function\. To avoid storing logs indefinitely, delete the log group, or [configure a retention period](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Working-with-log-groups-and-streams.html#SettingLogRetention) after which logs are deleted automatically\. \ No newline at end of file diff --git a/doc_source/ruby-package.md b/doc_source/ruby-package.md deleted file mode 100644 index e6e03092..00000000 --- a/doc_source/ruby-package.md +++ /dev/null @@ -1,96 +0,0 @@ -# AWS Lambda deployment package in Ruby - -A deployment package is a ZIP archive that contains your function code and dependencies\. You need to create a deployment package if you use the Lambda API to manage functions, or if you need to include libraries and dependencies other than the AWS SDK\. You can upload the package directly to Lambda, or you can use an Amazon S3 bucket, and then upload it to Lambda\. If the deployment package is larger than 50 MB, you must use Amazon S3\. - -If you use the Lambda [console editor](code-editor.md) to author your function, the console manages the deployment package\. You can use this method as long as you don't need to add any libraries\. You can also use it to update a function that already has libraries in the deployment package, as long as the total size doesn't exceed 3 MB\. - -**Note** -To keep your deployment package size small, package your function's dependencies in layers\. Layers let you manage your dependencies independently, can be used by multiple functions, and can be shared with other accounts\. For details, see [AWS Lambda layers](configuration-layers.md)\. - -**Topics** -+ [Updating a function with no dependencies](#ruby-package-codeonly) -+ [Updating a function with additional dependencies](#ruby-package-dependencies) - -## Updating a function with no dependencies - -To update a function by using the Lambda API, use the [UpdateFunctionCode](API_UpdateFunctionCode.md) operation\. Create an archive that contains your function code, and upload it using the AWS CLI\. - -**To update a Ruby function with no dependencies** - -1. Create a ZIP archive\. - - ``` - ~/my-function$ zip function.zip function.rb - ``` - -1. Use the `update-function-code` command to upload the package\. - - ``` - ~/my-function$ aws lambda update-function-code --function-name my-function --zip-file fileb://function.zip - { - "FunctionName": "my-function", - "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function", - "Runtime": "ruby2.5", - "Role": "arn:aws:iam::123456789012:role/lambda-role", - "Handler": "function.handler", - "CodeSha256": "Qf0hMc1I2di6YFMi9aXm3JtGTmcDbjniEuiYonYptAk=", - "Version": "$LATEST", - "TracingConfig": { - "Mode": "Active" - }, - "RevisionId": "983ed1e3-ca8e-434b-8dc1-7d72ebadd83d", - ... - } - ``` - -## Updating a function with additional dependencies - -If your function depends on libraries other than the AWS SDK for Ruby, install them to a local directory with [Bundler](https://bundler.io/), and include them in your deployment package\. - -**To update a Ruby function with dependencies** - -1. Install libraries in the vendor directory with the `bundle` command\. - - ``` - ~/my-function$ bundle install --path vendor/bundle - Fetching gem metadata from https://rubygems.org/.............. - Resolving dependencies... - Fetching aws-eventstream 1.0.1 - Installing aws-eventstream 1.0.1 - ... - ``` - - The `--path` installs the gems in the project directory instead of the system location, and sets this as the default path for future installations\. To later install gems globally, use the `--system` option\. - -1. Create a ZIP archive\. - - ``` - package$ zip -r function.zip function.rb vendor - adding: function.rb (deflated 37%) - adding: vendor/ (stored 0%) - adding: vendor/bundle/ (stored 0%) - adding: vendor/bundle/ruby/ (stored 0%) - adding: vendor/bundle/ruby/2.7.0/ (stored 0%) - adding: vendor/bundle/ruby/2.7.0/build_info/ (stored 0%) - adding: vendor/bundle/ruby/2.7.0/cache/ (stored 0%) - adding: vendor/bundle/ruby/2.7.0/cache/aws-eventstream-1.0.1.gem (deflated 36%) - ... - ``` - -1. Update the function code\. - - ``` - ~/my-function$ aws lambda update-function-code --function-name my-function --zip-file fileb://function.zip - { - "FunctionName": "my-function", - "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function", - "Runtime": "ruby2.5", - "Role": "arn:aws:iam::123456789012:role/lambda-role", - "Handler": "function.handler", - "CodeSize": 300, - "CodeSha256": "Qf0hMc1I2di6YFMi9aXm3JtGTmcDbjniEuiYonYptAk=", - "Version": "$LATEST", - "RevisionId": "983ed1e3-ca8e-434b-8dc1-7d72ebadd83d", - ... - } - ``` \ No newline at end of file diff --git a/doc_source/runtime-support-policy.md b/doc_source/runtime-support-policy.md deleted file mode 100644 index 2286fa4d..00000000 --- a/doc_source/runtime-support-policy.md +++ /dev/null @@ -1,20 +0,0 @@ -# Runtime support policy - -[AWS Lambda runtimes](lambda-runtimes.md) are built around a combination of operating system, programming language, and software libraries that are subject to maintenance and security updates\. When a component of a runtime is no longer supported for security updates, Lambda deprecates the runtime\. - -Deprecation occurs in two phases\. During the first phase, you can no longer create functions that use the deprecated runtime\. For at least 30 days, you can continue to update existing functions that use the deprecated runtime\. After this period, both function creation and updates are disabled permanently\. However, the function continues to be available to process invocation events\. - -**Note** -Python 2\.7 reached end\-of\-life on January 1st, 2020\. However, the Python 2\.7 runtime is still supported and is not scheduled to be deprecated at this time\. For details, see [Continued support for Python 2\.7 on AWS Lambda](https://aws.amazon.com/blogs/compute/continued-support-for-python-2-7-on-aws-lambda/)\. - -In most cases, the end\-of\-life date of a language version or operating system is known well in advance\. If you have functions running on a runtime that will be deprecated in the next 60 days, Lambda notifies you by email that you should prepare by migrating your function to a supported runtime\. In some cases, such as security issues that require a backwards\-incompatible update, or software that doesn't support a long\-term support \(LTS\) schedule, advance notice might not be possible\. - -**Language and framework support policies** -+ **Node\.js** – [github\.com](https://github.com/nodejs/Release#release-schedule) -+ **Python** – [devguide\.python\.org](https://devguide.python.org/#status-of-python-branches) -+ **Ruby** – [www\.ruby\-lang\.org](https://www.ruby-lang.org/en/downloads/branches/) -+ **Java** – [www\.oracle\.com](https://www.oracle.com/technetwork/java/java-se-support-roadmap.html) and [aws\.amazon\.com/corretto](https://aws.amazon.com/corretto/faqs/) -+ **Go** – [golang\.org](https://golang.org/s/release) -+ **\.NET Core** – [dotnet\.microsoft\.com](https://dotnet.microsoft.com/platform/support/policy/dotnet-core) - -After a runtime is deprecated, Lambda might retire it completely at any time by disabling invocation\. Deprecated runtimes aren't eligible for security updates or technical support\. Before retiring a runtime, Lambda sends additional notifications to affected customers\. No runtimes are scheduled to be retired at this time\. \ No newline at end of file diff --git a/doc_source/runtimes-api.md b/doc_source/runtimes-api.md deleted file mode 100644 index 6335e4fb..00000000 --- a/doc_source/runtimes-api.md +++ /dev/null @@ -1,104 +0,0 @@ -# AWS Lambda runtime interface - -AWS Lambda provides an HTTP API for [custom runtimes](runtimes-custom.md) to receive invocation events from Lambda and send response data back within the Lambda [execution environment](lambda-runtimes.md)\. - -The OpenAPI specification for the runtime API version **2018\-06\-01** is available here: [runtime\-api\.zip](samples/runtime-api.zip) - -Runtimes get an endpoint from the `AWS_LAMBDA_RUNTIME_API` environment variable, add the API version, and use the following resource paths to interact with the API\. - -**Example Request** - -``` -curl "http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/next" -``` - -**Topics** -+ [Next invocation](#runtimes-api-next) -+ [Invocation response](#runtimes-api-response) -+ [Invocation error](#runtimes-api-invokeerror) -+ [Initialization error](#runtimes-api-initerror) - -## Next invocation - -**Path** – `/runtime/invocation/next` - -**Method** – **GET** - -Retrieves an invocation event\. The response body contains the payload from the invocation, which is a JSON document that contains event data from the function trigger\. The response headers contain additional data about the invocation\. - -**Response headers** -+ `Lambda-Runtime-Aws-Request-Id` – The request ID, which identifies the request that triggered the function invocation\. - - For example, `8476a536-e9f4-11e8-9739-2dfe598c3fcd`\. -+ `Lambda-Runtime-Deadline-Ms` – The date that the function times out in Unix time milliseconds\. - - For example, `1542409706888`\. -+ `Lambda-Runtime-Invoked-Function-Arn` – The ARN of the Lambda function, version, or alias that's specified in the invocation\. - - For example, `arn:aws:lambda:us-east-2:123456789012:function:custom-runtime`\. -+ `Lambda-Runtime-Trace-Id` – The [AWS X\-Ray tracing header](https://docs.aws.amazon.com/xray/latest/devguide/xray-concepts.html#xray-concepts-tracingheader)\. - - For example, `Root=1-5bef4de7-ad49b0e87f6ef6c87fc2e700;Parent=9a9197af755a6419;Sampled=1`\. -+ `Lambda-Runtime-Client-Context` – For invocations from the AWS Mobile SDK, data about the client application and device\. -+ `Lambda-Runtime-Cognito-Identity` – For invocations from the AWS Mobile SDK, data about the Amazon Cognito identity provider\. - -Call `/runtime/invocation/next` to get the invocation event, and pass it to the function handler for processing\. Do not set a timeout on the `GET` call\. Between when Lambda bootstraps the runtime and when the runtime has an event to return, the runtime process may be frozen for several seconds\. - -The request ID tracks the invocation within Lambda\. Use it to specify the invocation when you send the response\. - -The tracing header contains the trace ID, parent ID, and sampling decision\. If the request is sampled, the request was sampled by Lambda or an upstream service\. The runtime should set the `_X_AMZN_TRACE_ID` with the value of the header\. The X\-Ray SDK reads this to get the IDs and determine whether to trace the request\. - -## Invocation response - -**Path** – `/runtime/invocation/AwsRequestId/response` - -**Method** – **POST** - -Sends an invocation response to Lambda\. After the runtime invokes the function handler, it posts the response from the function to the invocation response path\. For synchronous invocations, Lambda then sends the response back to the client\. - -**Example Success request** - -``` -REQUEST_ID=156cb537-e2d4-11e8-9b34-d36013741fb9 -curl -X POST "http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/$REQUEST_ID/response" -d "SUCCESS" -``` - -## Invocation error - -**Path** – `/runtime/invocation/AwsRequestId/error` - -**Method** – **POST** - -If the function returns an error, the runtime formats the error into a JSON document, and posts it to the invocation error path\. - -**Example Request body** - -``` -{ - "errorMessage" : "Error parsing event data.", - "errorType" : "InvalidEventDataException" -} -``` - -**Example Error request** - -``` -REQUEST_ID=156cb537-e2d4-11e8-9b34-d36013741fb9 -ERROR="{\"errorMessage\" : \"Error parsing event data.\", \"errorType\" : \"InvalidEventDataException\"}" -curl -X POST "http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/$REQUEST_ID/error" -d "$ERROR" --header "Lambda-Runtime-Function-Error-Type: Unhandled" -``` - -## Initialization error - -**Path** – `/runtime/init/error` - -**Method** – **POST** - -If the runtime encounters an error during initialization, it posts an error message to the initialization error path\. - -**Example Initialization error request** - -``` -ERROR="{\"errorMessage\" : \"Failed to load function.\", \"errorType\" : \"InvalidFunctionException\"}" -curl -X POST "http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/init/error" -d "$ERROR" --header "Lambda-Runtime-Function-Error-Type: Unhandled" -``` \ No newline at end of file diff --git a/doc_source/runtimes-context.md b/doc_source/runtimes-context.md deleted file mode 100644 index dcc433ba..00000000 --- a/doc_source/runtimes-context.md +++ /dev/null @@ -1,12 +0,0 @@ -# AWS Lambda execution context - -When AWS Lambda executes your Lambda function, it provisions and manages the resources needed to run your Lambda function\. When you create a Lambda function, you specify configuration information, such as the amount of memory and maximum execution time that you want to allow for your Lambda function\. When a Lambda function is invoked, AWS Lambda launches an execution context based on the configuration settings you provide\. The execution context is a temporary runtime environment that initializes any external dependencies of your Lambda function code, such as database connections or HTTP endpoints\. This affords subsequent invocations better performance because there is no need to "cold\-start" or initialize those external dependencies, as explained below\. - -It takes time to set up an execution context and do the necessary "bootstrapping", which adds some latency each time the Lambda function is invoked\. You typically see this latency when a Lambda function is invoked for the first time or after it has been updated because AWS Lambda tries to reuse the execution context for subsequent invocations of the Lambda function\. - -After a Lambda function is executed, AWS Lambda maintains the execution context for some time in anticipation of another Lambda function invocation\. In effect, the service freezes the execution context after a Lambda function completes, and thaws the context for reuse, if AWS Lambda chooses to reuse the context when the Lambda function is invoked again\. This execution context reuse approach has the following implications: -+ Objects declared outside of the function's handler method remain initialized, providing additional optimization when the function is invoked again\. For example, if your Lambda function establishes a database connection, instead of reestablishing the connection, the original connection is used in subsequent invocations\. We suggest adding logic in your code to check if a connection exists before creating one\. -+ Each execution context provides 512 MB of additional disk space in the `/tmp` directory\. The directory content remains when the execution context is frozen, providing transient cache that can be used for multiple invocations\. You can add extra code to check if the cache has the data that you stored\. For information on deployment limits, see [AWS Lambda limits](gettingstarted-limits.md)\. -+ Background processes or callbacks initiated by your Lambda function that did not complete when the function ended resume if AWS Lambda chooses to reuse the execution context\. You should make sure any background processes or callbacks in your code are complete before the code exits\. - -When you write your Lambda function code, do not assume that AWS Lambda automatically reuses the execution context for subsequent function invocations\. Other factors may dictate a need for AWS Lambda to create a new execution context, which can lead to unexpected results, such as database connection failures\. \ No newline at end of file diff --git a/doc_source/runtimes-custom.md b/doc_source/runtimes-custom.md deleted file mode 100644 index 3b1f3851..00000000 --- a/doc_source/runtimes-custom.md +++ /dev/null @@ -1,74 +0,0 @@ -# Custom AWS Lambda runtimes - -You can implement an AWS Lambda runtime in any programming language\. A runtime is a program that runs a Lambda function's handler method when the function is invoked\. You can include a runtime in your function's deployment package in the form of an executable file named `bootstrap`\. - -A runtime is responsible for running the function's setup code, reading the handler name from an environment variable, and reading invocation events from the Lambda runtime API\. The runtime passes the event data to the function handler, and posts the response from the handler back to Lambda\. - -Your custom runtime runs in the standard Lambda [execution environment](lambda-runtimes.md)\. It can be a shell script, a script in a language that's included in Amazon Linux, or a binary executable file that's compiled in Amazon Linux\. - -To get started with custom runtimes, see [Tutorial – Publishing a custom runtime](runtimes-walkthrough.md)\. You can also explore a custom runtime implemented in C\+\+ at [awslabs/aws\-lambda\-cpp](https://github.com/awslabs/aws-lambda-cpp) on GitHub\. - -**Topics** -+ [Using a custom runtime](#runtimes-custom-use) -+ [Building a custom runtime](#runtimes-custom-build) - -## Using a custom runtime - -To use a custom runtime, set your function's runtime to `provided`\. The runtime can be included in your function's deployment package, or in a [layer](configuration-layers.md)\. - -**Example function\.zip** - -``` -. -├── bootstrap -├── function.sh -``` - -If there's a file named `bootstrap` in your deployment package, Lambda executes that file\. If not, Lambda looks for a runtime in the function's layers\. If the bootstrap file isn't found or isn't executable, your function returns an error upon invocation\. - -## Building a custom runtime - -A custom runtime's entry point is an executable file named `bootstrap`\. The bootstrap file can be the runtime, or it can invoke another file that creates the runtime\. The following example uses a bundled version of Node\.js to execute a JavaScript runtime in a separate file named `runtime.js`\. - -**Example bootstrap** - -``` -#!/bin/sh -cd $LAMBDA_TASK_ROOT -./node-v11.1.0-linux-x64/bin/node runtime.js -``` - -Your runtime code is responsible for completing some initialization tasks\. Then it processes invocation events in a loop until it's terminated\. The initialization tasks run once [per instance of the function](runtimes-context.md) to prepare the environment to handle invocations\. - -**Initialization tasks** -+ **Retrieve settings** – Read environment variables to get details about the function and environment\. - + `_HANDLER` – The location to the handler, from the function's configuration\. The standard format is `file.method`, where `file` is the name of the file without an extension, and `method` is the name of a method or function that's defined in the file\. - + `LAMBDA_TASK_ROOT` – The directory that contains the function code\. - + `AWS_LAMBDA_RUNTIME_API` – The host and port of the runtime API\. - - See [Runtime environment variables](configuration-envvars.md#configuration-envvars-runtime) for a full list of available variables\. -+ **Initialize the function** – Load the handler file and run any global or static code that it contains\. Functions should create static resources like SDK clients and database connections once, and reuse them for multiple invocations\. -+ **Handle errors** – If an error occurs, call the [initialization error](runtimes-api.md#runtimes-api-initerror) API and exit immediately\. - -Initialization counts towards billed execution time and timeout\. When an execution triggers the initialization of a new instance of your function, you can see the initialization time in the logs and [AWS X\-Ray trace](lambda-x-ray.md)\. - -**Example Log** - -``` -REPORT RequestId: f8ac1208... Init Duration: 48.26 ms Duration: 237.17 ms Billed Duration: 300 ms Memory Size: 128 MB Max Memory Used: 26 MB -``` - -![\[Initialization time in an X-Ray trace.\]](http://docs.aws.amazon.com/lambda/latest/dg/images/runtimes-custom-init.png) - -While it runs, a runtime uses the [Lambda runtime interface](runtimes-api.md) to manage incoming events and report errors\. After completing initialization tasks, the runtime processes incoming events in a loop\. In your runtime code, perform the following steps in order\. - -**Processing tasks** -+ **Get an event** – Call the [next invocation](runtimes-api.md#runtimes-api-next) API to get the next event\. The response body contains the event data\. Response headers contain the request ID and other information\. -+ **Propagate the tracing header** – Get the X\-Ray tracing header from the `Lambda-Runtime-Trace-Id` header in the API response\. Set the `_X_AMZN_TRACE_ID` environment variable locally with the same value\. The X\-Ray SDK uses this value to connect trace data between services\. -+ **Create a context object** – Create an object with context information from environment variables and headers in the API response\. -+ **Invoke the function handler** – Pass the event and context object to the handler\. -+ **Handle the response** – Call the [invocation response](runtimes-api.md#runtimes-api-response) API to post the response from the handler\. -+ **Handle errors** – If an error occurs, call the [invocation error](runtimes-api.md#runtimes-api-invokeerror) API\. -+ **Cleanup** – Release unused resources, send data to other services, or perform additional tasks before getting the next event\. - -You can include the runtime in your function's deployment package, or distribute the runtime separately in a function layer\. For an example walkthrough, see [Tutorial – Publishing a custom runtime](runtimes-walkthrough.md)\. \ No newline at end of file diff --git a/doc_source/runtimes-walkthrough.md b/doc_source/runtimes-walkthrough.md deleted file mode 100644 index 3531cb0b..00000000 --- a/doc_source/runtimes-walkthrough.md +++ /dev/null @@ -1,289 +0,0 @@ -# Tutorial – Publishing a custom runtime - -In this tutorial, you create a Lambda function with a custom runtime\. You start by including the runtime in the function's deployment package\. Then you migrate it to a layer that you manage independently from the function\. Finally, you share the runtime layer with the world by updating its resource\-based permissions policy\. - -## Prerequisites - -This tutorial assumes that you have some knowledge of basic Lambda operations and the Lambda console\. If you haven't already, follow the instructions in [Getting started with AWS Lambda](getting-started.md) to create your first Lambda function\. - -To follow the procedures in this guide, you will need a command line terminal or shell to run commands\. Commands are shown in listings preceded by a prompt symbol \($\) and the name of the current directory, when appropriate: - -``` -~/lambda-project$ this is a command -this is output -``` - -For long commands, an escape character \(`\`\) is used to split a command over multiple lines\. - -On Linux and macOS, use your preferred shell and package manager\. On Windows 10, you can [install the Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows\-integrated version of Ubuntu and Bash\. - -You need an IAM role to create a Lambda function\. The role needs permission to send logs to CloudWatch Logs and access the AWS services that your function uses\. If you don't have a role for function development, create one now\. - -**To create an execution role** - -1. Open the [roles page](https://console.aws.amazon.com/iam/home#/roles) in the IAM console\. - -1. Choose **Create role**\. - -1. Create a role with the following properties\. - + **Trusted entity** – **Lambda**\. - + **Permissions** – **AWSLambdaBasicExecutionRole**\. - + **Role name** – **lambda\-role**\. - - The **AWSLambdaBasicExecutionRole** policy has the permissions that the function needs to write logs to CloudWatch Logs\. - -## Create a function - -Create a Lambda function with a custom runtime\. This example includes two files, a runtime `bootstrap` file, and a function handler\. Both are implemented in Bash\. - -The runtime loads a function script from the deployment package\. It uses two variables to locate the script\. `LAMBDA_TASK_ROOT` tells it where the package was extracted, and `_HANDLER` includes the name of the script\. - -**Example bootstrap** - -``` -#!/bin/sh - -set -euo pipefail - -# Initialization - load function handler -source $LAMBDA_TASK_ROOT/"$(echo $_HANDLER | cut -d. -f1).sh" - -# Processing -while true -do - HEADERS="$(mktemp)" - # Get an event. The HTTP request will block until one is received - EVENT_DATA=$(curl -sS -LD "$HEADERS" -X GET "http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/next") - - # Extract request ID by scraping response headers received above - REQUEST_ID=$(grep -Fi Lambda-Runtime-Aws-Request-Id "$HEADERS" | tr -d '[:space:]' | cut -d: -f2) - - # Execute the handler function from the script - RESPONSE=$($(echo "$_HANDLER" | cut -d. -f2) "$EVENT_DATA") - - # Send the response - curl -X POST "http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/$REQUEST_ID/response" -d "$RESPONSE" -done -``` - -After loading the script, the runtime processes events in a loop\. It uses the runtime API to retrieve an invocation event from Lambda, passes the event to the handler, and posts the response back to Lambda\. To get the request ID, the runtime saves the headers from the API response to a temporary file, and reads the `Lambda-Runtime-Aws-Request-Id` header from the file\. - -**Note** -Runtimes have additional responsibilities, including error handling, and providing context information to the handler\. For details, see [Building a custom runtime](runtimes-custom.md#runtimes-custom-build)\. - -The script defines a handler function that takes event data, logs it to `stderr`, and returns it\. - -**Example function\.sh** - -``` -function handler () { - EVENT_DATA=$1 - echo "$EVENT_DATA" 1>&2; - RESPONSE="Echoing request: '$EVENT_DATA'" - - echo $RESPONSE -} -``` - -Save both files in a project directory named `runtime-tutorial`\. - -``` -runtime-tutorial -├ bootstrap -└ function.sh -``` - -Make the files executable and add them to a ZIP archive\. - -``` -runtime-tutorial$ chmod 755 function.sh bootstrap -runtime-tutorial$ zip function.zip function.sh bootstrap - adding: function.sh (deflated 24%) - adding: bootstrap (deflated 39%) -``` - -Create a function named `bash-runtime`\. - -``` -runtime-tutorial$ aws lambda create-function --function-name bash-runtime \ ---zip-file fileb://function.zip --handler function.handler --runtime provided \ ---role arn:aws:iam::123456789012:role/lambda-role -{ - "FunctionName": "bash-runtime", - "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:bash-runtime", - "Runtime": "provided", - "Role": "arn:aws:iam::123456789012:role/lambda-role", - "Handler": "function.handler", - "CodeSha256": "mv/xRv84LPCxdpcbKvmwuuFzwo7sLwUO1VxcUv3wKlM=", - "Version": "$LATEST", - "TracingConfig": { - "Mode": "PassThrough" - }, - "RevisionId": "2e1d51b0-6144-4763-8e5c-7d5672a01713", - ... -} -``` - -Invoke the function and verify the response\. - -``` -runtime-tutorial$ aws lambda invoke --function-name bash-runtime --payload '{"text":"Hello"}' response.txt -{ - "StatusCode": 200, - "ExecutedVersion": "$LATEST" -} -runtime-tutorial$ cat response.txt -Echoing request: '{"text":"Hello"}' -``` - -## Create a layer - -To separate the runtime code from the function code, create a layer that only contains the runtime\. Layers let you develop your function's dependencies independently, and can reduce storage usage when you use the same layer with multiple functions\. - -Create a layer archive that contains the `bootstrap` file\. - -``` -runtime-tutorial$ zip runtime.zip bootstrap - adding: bootstrap (deflated 39%) -``` - -Create a layer with the `publish-layer-version` command\. - -``` -runtime-tutorial$ aws lambda publish-layer-version --layer-name bash-runtime --zip-file fileb://runtime.zip - { - "Content": { - "Location": "https://awslambda-us-west-2-layers.s3.us-west-2.amazonaws.com/snapshots/123456789012/bash-runtime-018c209b...", - "CodeSha256": "bXVLhHi+D3H1QbDARUVPrDwlC7bssPxySQqt1QZqusE=", - "CodeSize": 584, - "UncompressedCodeSize": 0 - }, - "LayerArn": "arn:aws:lambda:us-west-2:123456789012:layer:bash-runtime", - "LayerVersionArn": "arn:aws:lambda:us-west-2:123456789012:layer:bash-runtime:1", - "Description": "", - "CreatedDate": "2018-11-28T07:49:14.476+0000", - "Version": 1 -} -``` - -This creates the first version of the layer\. - -## Update the function - -To use the runtime layer with the function, configure the function to use the layer, and remove the runtime code from the function\. - -Update the function configuration to pull in the layer\. - -``` -runtime-tutorial$ aws lambda update-function-configuration --function-name bash-runtime \ ---layers arn:aws:lambda:us-west-2:123456789012:layer:bash-runtime:1 -{ - "FunctionName": "bash-runtime", - "Layers": [ - { - "Arn": "arn:aws:lambda:us-west-2:123456789012:layer:bash-runtime:1", - "CodeSize": 584, - "UncompressedCodeSize": 679 - } - ] - ... -} -``` - -This adds the runtime to the function in the `/opt` directory\. Lambda uses this runtime, but only if you remove it from the function's deployment package\. Update the function code to only include the handler script\. - -``` -runtime-tutorial$ zip function-only.zip function.sh - adding: function.sh (deflated 24%) -runtime-tutorial$ aws lambda update-function-code --function-name bash-runtime --zip-file fileb://function-only.zip -{ - "FunctionName": "bash-runtime", - "CodeSize": 270, - "Layers": [ - { - "Arn": "arn:aws:lambda:us-west-2:123456789012:layer:bash-runtime:7", - "CodeSize": 584, - "UncompressedCodeSize": 679 - } - ] - ... -} -``` - -Invoke the function to verify that it works with the runtime layer\. - -``` -runtime-tutorial$ aws lambda invoke --function-name bash-runtime --payload '{"text":"Hello"}' response.txt -{ - "StatusCode": 200, - "ExecutedVersion": "$LATEST" -} -runtime-tutorial$ cat response.txt -Echoing request: '{"text":"Hello"}' -``` - -## Update the runtime - -To log information about the execution environment, update the runtime script to output environment variables\. - -**Example bootstrap** - -``` -#!/bin/sh - -set -euo pipefail - -echo "## Environment variables:" -env - -# Initialization - load function handler -source $LAMBDA_TASK_ROOT/"$(echo $_HANDLER | cut -d. -f1).sh" -... -``` - -Create a second version of the layer with the new code\. - -``` -runtime-tutorial$ zip runtime.zip bootstrap -updating: bootstrap (deflated 39%) -runtime-tutorial$ aws lambda publish-layer-version --layer-name bash-runtime --zip-file fileb://runtime.zip -``` - -Configure the function to use the new version of the layer\. - -``` -runtime-tutorial$ aws lambda update-function-configuration --function-name bash-runtime \ ---layers arn:aws:lambda:us-west-2:123456789012:layer:bash-runtime:2 -``` - -## Share the layer - -Add a permission statement to your runtime layer to share it with other accounts\. - -``` -runtime-tutorial$ aws lambda add-layer-version-permission --layer-name bash-runtime --version-number 2 \ ---principal "*" --statement-id publish --action lambda:GetLayerVersion -{ - "Statement": "{\"Sid\":\"publish\",\"Effect\":\"Allow\",\"Principal\":\"*\",\"Action\":\"lambda:GetLayerVersion\",\"Resource\":\"arn:aws:lambda:us-west-2:123456789012:layer:bash-runtime:2\"}", - "RevisionId": "9d5fe08e-2a1e-4981-b783-37ab551247ff" -} -``` - -You can add multiple statements that each grant permission to a single account, accounts in an organization, or all accounts\. - -## Clean up - -Delete each version of the layer\. - -``` -runtime-tutorial$ aws lambda delete-layer-version --layer-name bash-runtime --version-number 1 -runtime-tutorial$ aws lambda delete-layer-version --layer-name bash-runtime --version-number 2 -``` - -Because the function holds a reference to version 2 of the layer, it still exists in Lambda\. The function continues to work, but functions can no longer be configured to use the deleted version\. If you then modify the list of layers on the function, you must specify a new version or omit the deleted layer\. - -Delete the tutorial function with the `delete-function` command\. - -``` -runtime-tutorial$ aws lambda delete-function --function-name bash-runtime -``` \ No newline at end of file diff --git a/doc_source/samples-blank.md b/doc_source/samples-blank.md deleted file mode 100644 index 6000ad44..00000000 --- a/doc_source/samples-blank.md +++ /dev/null @@ -1,246 +0,0 @@ -# Blank function sample application for AWS Lambda - -The blank function sample application is a starter application that demonstrates common operations in Lambda with a function that calls the Lambda API\. It shows the use of logging, environment variables, AWS X\-Ray tracing, layers, unit tests and the AWS SDK\. Explore this application to learn about building Lambda functions in your programming language, or use it as a starting point for your own projects\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/sample-blank.png) - -Variants of this sample application are available for the following languages: - -**Variants** -+ Node\.js – [blank\-nodejs](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/blank-nodejs)\. -+ Python – [blank\-python](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/blank-python)\. -+ Ruby – [blank\-ruby](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/blank-ruby)\. -+ Java – [blank\-java](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/blank-java)\. -+ Go – [blank\-go](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/blank-go)\. -+ C\# – [blank\-csharp](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/blank-csharp)\. -+ PowerShell – [blank\-powershell](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/blank-powershell)\. - -The examples in this topic highlight code from the Node\.js version, but the details are generally applicable to all variants\. - -You can deploy the sample in a few minutes with the AWS CLI and AWS CloudFormation\. Follow the instructions in the [README](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/blank-nodejs) to download, configure, and deploy it in your account\. - -**Topics** -+ [Architecture and handler code](#samples-blank-architecture) -+ [Deployment automation with AWS CloudFormation and the AWS CLI](#samples-blank-automation) -+ [Instrumentation with the AWS X\-Ray](#samples-blank-instrumentation) -+ [Dependency management with layers](#samples-blank-dependencies) - -## Architecture and handler code - -The sample application consists of function code, an AWS CloudFormation template, and supporting resources\. When you deploy the sample, you use the following AWS services: -+ AWS Lambda – Runs function code, sends logs to CloudWatch Logs, and sends trace data to X\-Ray\. The function also calls the Lambda API to get details about the account's limits and usage in the current Region\. -+ [AWS X\-Ray](https://aws.amazon.com/xray) – Collects trace data, indexes traces for search, and generates a service map\. -+ [Amazon CloudWatch](https://aws.amazon.com/cloudwatch) – Stores logs and metrics\. -+ [AWS Identity and Access Management \(IAM\)](https://aws.amazon.com/iam) – Grants permission\. -+ [Amazon Simple Storage Service \(Amazon S3\)](https://aws.amazon.com/s3) – Stores the function's deployment package during deployment\. -+ [AWS CloudFormation](https://aws.amazon.com/cloudformation) – Creates application resources and deploys function code\. - -Standard charges apply for each service\. For more information, see [AWS Pricing](https://aws.amazon.com/pricing)\. - -The function code shows a basic workflow for processing an event\. The handler takes an Amazon Simple Queue Service \(Amazon SQS\) event as input and iterates through the records that it contains, logging the contents of each message\. It logs the contents of the event, the context object, and environment variables\. Then it makes a call with the AWS SDK and passes the response back to the Lambda runtime\. - -**Example [blank\-nodejs/function/index\.js](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/blank-nodejs/function/index.js) – Handler code** - -``` -// Handler -exports.handler = async function(event, context) { - event.Records.forEach(record => { - console.log(record.body) - }) - console.log('## ENVIRONMENT VARIABLES: ' + serialize(process.env)) - console.log('## CONTEXT: ' + serialize(context)) - console.log('## EVENT: ' + serialize(event)) - - return getAccountSettings() -} - -// Use SDK client -var getAccountSettings = function(){ - return lambda.getAccountSettings().promise() -} - -var serialize = function(object) { - return JSON.stringify(object, null, 2) -} -``` - -The input/output types for the handler and support for asynchronous programming vary per runtime\. In this example, the handler method is `async`, so in Node\.js this means that it must return a promise back to the runtime\. The Lambda runtime waits for the promise to be resolved and returns the response to the invoker\. If the function code or AWS SDK client return an error, the runtime formats the error into a JSON document and returns that\. - -The sample application doesn't include an Amazon SQS queue to send events, but uses an event from Amazon SQS \([event\.json](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/blank-nodejs/event.json)\) to illustrate how events are processed\. To add an Amazon SQS queue to your application, see [Using AWS Lambda with Amazon SQS](with-sqs.md)\. - -## Deployment automation with AWS CloudFormation and the AWS CLI - -The sample application's resources are defined in an AWS CloudFormation template and deployed with the AWS CLI\. The project includes simple shell scripts that automate the process of setting up, deploying, invoking, and tearing down the application\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/sample-blank-stack.png) - -The application template uses an AWS Serverless Application Model \(AWS SAM\) resource type to define the model\. AWS SAM simplifies template authoring for serverless applications by automating the definition of execution roles, APIs, and other resources\. - -The template defines the resources in the application *stack*\. This includes the function, its execution role, and a Lambda layer that provides the function's library dependencies\. The stack does not include the bucket that the AWS CLI uses during deployment or the CloudWatch Logs log group\. - -**Example [blank\-nodejs/template\.yml](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/blank-nodejs/template.yml) – Serverless resource** - -``` -AWSTemplateFormatVersion: '2010-09-09' -Transform: 'AWS::Serverless-2016-10-31' -Description: An AWS Lambda application that calls the Lambda API. -Resources: - function: - Type: [AWS::Serverless::Function](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-function.html) - Properties: - Handler: index.handler - Runtime: nodejs12.x - CodeUri: function/. - Description: Call the AWS Lambda API - Timeout: 10 - # Function's execution role - Policies: - - AWSLambdaBasicExecutionRole - - AWSLambdaReadOnlyAccess - - AWSXrayWriteOnlyAccess - Tracing: Active - Layers: - - !Ref libs - libs: - Type: [AWS::Serverless::LayerVersion](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-layerversion.html) - Properties: - LayerName: blank-nodejs-lib - Description: Dependencies for the blank sample app. - ContentUri: lib/. - CompatibleRuntimes: - - nodejs12.x -``` - -When you deploy the application, AWS CloudFormation applies the AWS SAM transform to the template to generate an AWS CloudFormation template with standard types such as `AWS::Lambda::Function` and `AWS::IAM::Role`\. - -**Example Processed template** - -``` -{ - "AWSTemplateFormatVersion": "2010-09-09", - "Description": "An AWS Lambda application that calls the Lambda API.", - "Resources": { - "function": { - "Type": "[AWS::Lambda::Function](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-function.html)", - "Properties": { - "Layers": [ - { - "Ref": "libs32xmpl61b2" - } - ], - "TracingConfig": { - "Mode": "Active" - }, - "Code": { - "S3Bucket": "lambda-artifacts-6b000xmpl1e9bf2a", - "S3Key": "3d3axmpl473d249d039d2d7a37512db3" - }, - "Description": "Call the AWS Lambda API", - "Tags": [ - { - "Value": "SAM", - "Key": "lambda:createdBy" - } - ], -``` - -In this example, the `Code` property specifies an object in an Amazon S3 bucket\. This corresponds to the local path in the `CodeUri` property in the project template: - -``` - CodeUri: function/. -``` - -To upload the project files to Amazon S3, the deployment script uses commands in the AWS CLI\. The `cloudformation package` command preprocesses the template, uploads artifacts, and replaces local paths with Amazon S3 object locations\. The `cloudformation deploy` command deploys the processed template with a AWS CloudFormation change set\. - -**Example [blank\-nodejs/3\-deploy\.sh](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/blank-nodejs/3-deploy.sh) – Package and deploy** - -``` -#!/bin/bash -set -eo pipefail -ARTIFACT_BUCKET=$(cat bucket-name.txt) -aws cloudformation package --template-file template.yml --s3-bucket $ARTIFACT_BUCKET --output-template-file out.yml -aws cloudformation deploy --template-file out.yml --stack-name blank-nodejs --capabilities CAPABILITY_NAMED_IAM -``` - -The first time you run this script, it creates a AWS CloudFormation stack named `blank-nodejs`\. If you make changes to the function code or template, you can run it again to update the stack\. - -The cleanup script \([blank\-nodejs/4\-cleanup\.sh](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/blank-nodejs/4-cleanup.sh)\) deletes the stack and optionally deletes the deployment bucket and function logs\. - -## Instrumentation with the AWS X\-Ray - -The sample function is configured for tracing with [AWS X\-Ray](https://console.aws.amazon.com/xray/home)\. With the tracing mode set to active, Lambda records timing information for a subset of invocations and sends it to X\-Ray\. X\-Ray processes the data to generate a *service map* that shows a client node and two service nodes: - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/blank-servicemap-basic.png) - -The first service node \(`AWS::Lambda`\) represents the Lambda service, which validates the invocation request and sends it to the function\. The second node, `AWS::Lambda::Function`, represents the function itself\. - -To record additional detail, the sample function uses the X\-Ray SDK\. With minimal changes to the function code, the X\-Ray SDK records details about calls made with the AWS SDK to AWS services\. - -**Example [blank\-nodejs/function/index\.js](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/blank-nodejs/function/index.js) – Instrumentation** - -``` -const AWSXRay = require('aws-xray-sdk-core') -const AWS = AWSXRay.captureAWS(require('aws-sdk')) - -// Create client outside of handler to reuse -const lambda = new AWS.Lambda() -``` - -Instrumenting the AWS SDK client adds an additional node to the service map and more detail in traces\. In this example, the service map shows the sample function calling the Lambda API to get details about storage and concurrency usage in the current Region\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/blank-servicemap.png) - -The trace shows timing details for the invocation, with subsegments for function initialization, invocation, and overhead\. The invocation subsegment has a subsegment for the AWS SDK call to the `GetAccountSettings` API operation\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/blank-trace.png) - -You can include the X\-Ray SDK and other libraries in your function's deployment package, or deploy them separately in a Lambda layer\. For Node\.js, Ruby, and Python, the Lambda runtime includes the AWS SDK in the execution environment\. - -## Dependency management with layers - -You can install libraries locally and include them in the deployment package that you upload to Lambda, but this has its drawbacks\. Larger file sizes cause increased deployment times and can prevent you from testing changes to your function code in the Lambda console\. To keep the deployment package small and avoid uploading dependencies that haven't changed, the sample app creates a [Lambda layer](configuration-layers.md) and associates it with the function\. - -**Example [blank\-nodejs/template\.yml](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/blank-nodejs/template.yml) – Dependency layer** - -``` -Resources: - function: - Type: AWS::Serverless::Function - Properties: - Handler: index.handler - Runtime: nodejs12.x - CodeUri: function/. - Description: Call the AWS Lambda API - Timeout: 10 - # Function's execution role - Policies: - - AWSLambdaBasicExecutionRole - - AWSLambdaReadOnlyAccess - - AWSXrayWriteOnlyAccess - Tracing: Active - Layers: - - !Ref libs - libs: - Type: AWS::Serverless::LayerVersion - Properties: - LayerName: blank-nodejs-lib - Description: Dependencies for the blank sample app. - ContentUri: lib/. - CompatibleRuntimes: - - nodejs12.x -``` - -The `2-build-layer.sh` script installs the function's dependencies with npm and places them in a folder with the [structure required by the Lambda runtime](configuration-layers.md#configuration-layers-path)\. - -**Example [2\-build\-layer\.sh](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/blank-nodejs/2-build-layer.sh) – Preparing the layer** - -``` -#!/bin/bash -set -eo pipefail -mkdir -p lib/nodejs -rm -rf node_modules lib/nodejs/node_modules -npm install --production -mv node_modules lib/nodejs/ -``` - -The first time that you deploy the sample application, the AWS CLI packages the layer separately from the function code and deploys both\. For subsequent deployments, the layer archive is only uploaded if the contents of the `lib` folder have changed\. \ No newline at end of file diff --git a/doc_source/samples-errorprocessor.md b/doc_source/samples-errorprocessor.md deleted file mode 100644 index c061d523..00000000 --- a/doc_source/samples-errorprocessor.md +++ /dev/null @@ -1,93 +0,0 @@ -# Error processor sample application for AWS Lambda - -The Error Processor sample application demonstrates the use of AWS Lambda to handle events from an [Amazon CloudWatch Logs subscription](services-cloudwatchlogs.md)\. CloudWatch Logs lets you invoke a Lambda function when a log entry matches a pattern\. The subscription in this application monitors the log group of a function for entries that contain the word `ERROR`\. It invokes a processor Lambda function in response\. The processor function retrieves the full log stream and trace data for the request that caused the error, and stores them for later use\. - -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/sample-errorprocessor.png) - -Function code is available in the following files: -+ Random error – [random\-error/index\.js](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/error-processor/random-error/index.js) -+ Processor – [processor/index\.js](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/error-processor/processor/index.js) - -You can deploy the sample in a few minutes with the AWS CLI and AWS CloudFormation\. Follow the instructions in the [README](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/error-processor) to download, configure, and deploy it in your account\. - -**Topics** -+ [Architecture and event structure](#sample-errorprocessor-architecture) -+ [Instrumentation with AWS X\-Ray](#sample-errorprocessor-instrumentation) -+ [AWS CloudFormation template and additional resources](#sample-errorprocessor-template) - -## Architecture and event structure - -The sample application uses the following AWS services\. -+ AWS Lambda – Runs function code, sends logs to CloudWatch Logs, and sends trace data to X\-Ray\. -+ Amazon CloudWatch Logs – Collects logs, and invokes a function when a log entry matches a filter pattern\. -+ AWS X\-Ray – Collects trace data, indexes traces for search, and generates a service map\. -+ Amazon Simple Storage Service \(Amazon S3\) – Stores deployment artifacts and application output\. - -Standard charges apply for each service\. - -A Lambda function in the application generates errors randomly\. When CloudWatch Logs detects the word `ERROR` in the function's logs, it sends an event to the processor function for processing\. - -**Example – CloudWatch Logs message event** - -``` -{ - "awslogs": { - "data": "H4sIAAAAAAAAAHWQT0/DMAzFv0vEkbLYcdJkt4qVXmCDteIAm1DbZKjS+kdpB0Jo350MhsQFyVLsZ+unl/fJWjeO5asrPgbH5..." - } -} -``` - -When it's decoded, the data contains details about the log event\. The function uses these details to identify the log stream, and parses the log message to get the ID of the request that caused the error\. - -**Example – Decoded CloudWatch Logs event data** - -``` -{ - "messageType": "DATA_MESSAGE", - "owner": "123456789012", - "logGroup": "/aws/lambda/lambda-error-processor-randomerror-1GD4SSDNACNP4", - "logStream": "2019/04/04/[$LATEST]63311769a9d742f19cedf8d2e38995b9", - "subscriptionFilters": [ - "lambda-error-processor-subscription-15OPDVQ59CG07" - ], - "logEvents": [ - { - "id": "34664632210239891980253245280462376874059932423703429141", - "timestamp": 1554415868243, - "message": "2019-04-04T22:11:08.243Z\t1d2c1444-efd1-43ec-b16e-8fb2d37508b8\tERROR\n" - } - ] -} -``` - -The processor function uses information from the CloudWatch Logs event to download the full log stream and X\-Ray trace for a request that caused an error\. It stores both in an Amazon S3 bucket\. To allow the log stream and trace time to finalize, the function waits for a short period of time before accessing the data\. - -## Instrumentation with AWS X\-Ray - -The application uses [AWS X\-Ray](lambda-x-ray.md) to trace function invocations and the calls that functions make to AWS services\. X\-Ray uses the trace data that it receives from functions to create a service map that helps you identify errors\. The following service map shows the random error function generating errors for some requests\. It also shows the processor function calling X\-Ray, CloudWatch Logs, and Amazon S3\. - -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/sample-errorprocessor-servicemap.png) - -The two Node\.js functions are configured for active tracing in the template, and are instrumented with the AWS X\-Ray SDK for Node\.js in code\. With active tracing, Lambda tags adds a tracing header to incoming requests and sends a trace with timing details to X\-Ray\. Additionally, the random error function uses the X\-Ray SDK to record the request ID and user information in annotations\. The annotations are attached to the trace, and you can use them to locate the trace for a specific request\. - -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/sample-errorprocessor-trace.png) - -The processor function gets the request ID from the CloudWatch Logs event, and uses the AWS SDK for JavaScript to search X\-Ray for that request\. It uses AWS SDK clients, which are instrumented with the X\-Ray SDK, to download the trace and log stream\. Then it stores them in the output bucket\. The X\-Ray SDK records these calls, and they appear as subsegments in the trace\. - -## AWS CloudFormation template and additional resources - -The application is implemented in two Node\.js modules and deployed with an AWS CloudFormation template and supporting shell scripts\. The template creates the processor function, the random error function, and the following supporting resources\. -+ Execution role – An IAM role that grants the functions permission to access other AWS services\. -+ Primer function – An additional function that invokes the random error function to create a log group\. -+ Custom resource – An AWS CloudFormation custom resource that invokes the primer function during deployment to ensure that the log group exists\. -+ CloudWatch Logs subscription – A subscription for the log stream that triggers the processor function when the word ERROR is logged\. -+ Resource\-based policy – A permission statement on the processor function that allows CloudWatch Logs to invoke it\. -+ Amazon S3 bucket – A storage location for output from the processor function\. - -View the template [template\.yml](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/error-processor/template.yml) on GitHub\. - -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/sample-errorprocessor-stack.png) - -To work around a limitation of Lambda's integration with AWS CloudFormation, the template creates an additional function that runs during deployments\. All Lambda functions come with a CloudWatch Logs log group that stores output from function executions\. However, the log group isn't created until the function is invoked for the first time\. - -To create the subscription, which depends on the existence of the log group, the application uses a third Lambda function to invoke the random error function\. The template includes the code for the primer function inline\. An AWS CloudFormation custom resource invokes it during deployment\. `DependsOn` properties ensure that the log stream and resource\-based policy are created prior to the subscription\. \ No newline at end of file diff --git a/doc_source/security-compliance.md b/doc_source/security-compliance.md deleted file mode 100644 index bf7e3550..00000000 --- a/doc_source/security-compliance.md +++ /dev/null @@ -1,14 +0,0 @@ -# Compliance validation for AWS Lambda - -Third\-party auditors assess the security and compliance of AWS Lambda as part of multiple AWS compliance programs\. These include SOC, PCI, FedRAMP, HIPAA, and others\. - -For a list of AWS services in scope of specific compliance programs, see [AWS services in scope by compliance program](http://aws.amazon.com/compliance/services-in-scope/)\. For general information, see [AWS compliance programs](http://aws.amazon.com/compliance/programs/)\. - -You can download third\-party audit reports using AWS Artifact\. For more information, see [Downloading reports in AWS artifact](https://docs.aws.amazon.com/artifact/latest/ug/downloading-documents.html)\. - -Your compliance responsibility when using Lambda is determined by the sensitivity of your data, your company's compliance objectives, and applicable laws and regulations\. AWS provides the following resources to help with compliance: -+ [Security and compliance quick start guides](http://aws.amazon.com/quickstart/?awsf.quickstart-homepage-filter=categories%23security-identity-compliance) – These deployment guides discuss architectural considerations and provide steps for deploying security\- and compliance\-focused baseline environments on AWS\. -+ [Architecting for HIPAA security and compliance whitepaper ](https://d0.awsstatic.com/whitepapers/compliance/AWS_HIPAA_Compliance_Whitepaper.pdf) – This whitepaper describes how companies can use AWS to create HIPAA\-compliant applications\. -+ [AWS compliance resources](http://aws.amazon.com/compliance/resources/) – This collection of workbooks and guides might apply to your industry and location\. -+ [AWS Config](https://docs.aws.amazon.com/config/latest/developerguide/evaluate-config.html) – This AWS service assesses how well your resource configurations comply with internal practices, industry guidelines, and regulations\. -+ [AWS Security Hub](https://docs.aws.amazon.com/securityhub/latest/userguide/what-is-securityhub.html) – This AWS service provides a comprehensive view of your security state within AWS that helps you check your compliance with security industry standards and best practices\. \ No newline at end of file diff --git a/doc_source/security-configuration.md b/doc_source/security-configuration.md deleted file mode 100644 index 9b557af4..00000000 --- a/doc_source/security-configuration.md +++ /dev/null @@ -1,7 +0,0 @@ -# Configuration and vulnerability analysis in AWS Lambda - -AWS Lambda provides [runtimes](lambda-runtimes.md) that run your function code in an Amazon Linux–based execution environment\. Lambda is responsible for keeping software in the runtime and execution environment up to date, releasing new runtimes for new languages and frameworks, and deprecating runtimes when the underlying software is no longer supported\. - -If you use additional libraries with your function, you're responsible for updating the libraries\. You can include additional libraries in the [deployment package](gettingstarted-features.md#gettingstarted-features-package), or in [layers](configuration-layers.md) that you attach to your function\. You can also build [custom runtimes](runtimes-custom.md) and use layers to share them with other accounts\. - -Lambda deprecates runtimes when the software on the runtime or its execution environment reaches end of life\. When Lambda deprecates a runtime, you're responsible for migrating your functions to a supported runtime for the same language or framework\. For details, see [Runtime support policy](runtime-support-policy.md)\. \ No newline at end of file diff --git a/doc_source/security-dataprotection.md b/doc_source/security-dataprotection.md deleted file mode 100644 index 5b19c204..00000000 --- a/doc_source/security-dataprotection.md +++ /dev/null @@ -1,38 +0,0 @@ -# Data protection in AWS Lambda - -AWS Lambda conforms to the AWS [shared responsibility model](http://aws.amazon.com/compliance/shared-responsibility-model/), which includes regulations and guidelines for data protection\. AWS is responsible for protecting the global infrastructure that runs all the AWS services\. AWS maintains control over data hosted on this infrastructure, including the security configuration controls for handling customer content and personal data\. AWS customers and APN partners, acting either as data controllers or data processors, are responsible for any personal data that they put in the AWS Cloud\. - -For data protection purposes, we recommend that you protect AWS account credentials and set up individual user accounts with AWS Identity and Access Management \(IAM\), so that each user is given only the permissions necessary to fulfill their job duties\. We also recommend that you secure your data in the following ways: -+ Use multi\-factor authentication \(MFA\) with each account\. -+ Use SSL/TLS to communicate with AWS resources\. -+ Set up API and user activity logging with AWS CloudTrail\. -+ Use AWS encryption solutions, along with all default security controls within AWS services\. -+ Use advanced managed security services such as Amazon Macie, which assists in discovering and securing personal data that is stored in Amazon S3\. - -We strongly recommend that you never put sensitive identifying information, such as your customers' account numbers, into free\-form fields or metadata such as function names and tags\. This includes when you work with Lambda or other AWS services using the console, API, AWS CLI, or AWS SDKs\. Any data that you enter into metadata might get picked up for inclusion in diagnostic logs\. When you provide a URL to an external server, don't include credentials information in the URL to validate your request to that server\. - -For more information about data protection, see the [AWS shared responsibility model and GDPR](http://aws.amazon.com/blogs/security/the-aws-shared-responsibility-model-and-gdpr/) blog post on the *AWS Security Blog*\. - -**Topics** -+ [Encryption in transit](#security-privacy-intransit) -+ [Encryption at rest](#security-privacy-atrest) - -## Encryption in transit - -Lambda API endpoints only support secure connections over HTTPS\. When you manage Lambda resources with the AWS Management Console, AWS SDK, or the Lambda API, all communication is encrypted with Transport Layer Security \(TLS\)\. - -For a full list of API endpoints, see [AWS Regions and endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html) in the AWS General Reference\. - -## Encryption at rest - -You can use environment variables to store secrets securely for use with Lambda functions\. Lambda always encrypts environment variables at rest\. - -Additionally, you can use the following features to customize how environment variables are encrypted\. -+ **Key configuration** – On a per\-function basis, you can configure Lambda to use an encryption key that you create and manage in AWS Key Management Service\. These are referred to as *customer managed* customer master keys \(CMKs\) or customer managed keys\. If you don't configure a customer managed key, Lambda uses an AWS managed CMK named `aws/lambda`, which Lambda creates in your account\. -+ **Encryption helpers** – The Lambda console lets you encrypt environment variable values client side, before sending them to Lambda\. This enhances security further by preventing secrets from being displayed unencrypted in the Lambda console, or in function configuration that's returned by the Lambda API\. The console also provides sample code that you can adapt to decrypt the values in your function handler\. - -For more information, see [Using AWS Lambda environment variables](configuration-envvars.md)\. - -Lambda always encrypts files that you upload to Lambda, including [deployment packages](gettingstarted-features.md#gettingstarted-features-package) and [layer archives](configuration-layers.md)\. - -Amazon CloudWatch Logs and AWS X\-Ray also encrypt data by default, and can be configured to use a customer managed key\. For details, see [Encrypt log data in CloudWatch Logs](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/encrypt-log-data-kms.html) and [Data protection in AWS X\-Ray](https://docs.aws.amazon.com/xray/latest/devguide/xray-console-encryption.html)\. \ No newline at end of file diff --git a/doc_source/security-iam.md b/doc_source/security-iam.md deleted file mode 100644 index a4f75681..00000000 --- a/doc_source/security-iam.md +++ /dev/null @@ -1,89 +0,0 @@ -# Identity and access management for AWS Lambda - -AWS Identity and Access Management \(IAM\) is an AWS service that helps an administrator securely control access to AWS resources\. IAM administrators control who can be *authenticated* \(signed in\) and *authorized* \(have permissions\) to use Lambda resources\. IAM is an AWS service that you can use with no additional charge\. - -**Topics** -+ [Audience](#security_iam_audience) -+ [Authenticating with identities](#security_iam_authentication) -+ [Managing access using policies](#security_iam_access-manage) -+ [How AWS Lambda works with IAM](security_iam_service-with-iam.md) -+ [AWS Lambda identity\-based policy examples](security_iam_id-based-policy-examples.md) -+ [Troubleshooting AWS Lambda identity and access](security_iam_troubleshoot.md) - -## Audience - -How you use AWS Identity and Access Management \(IAM\) differs, depending on the work you do in Lambda\. - -**Service user** – If you use the Lambda service to do your job, then your administrator provides you with the credentials and permissions that you need\. As you use more Lambda features to do your work, you might need additional permissions\. Understanding how access is managed can help you request the right permissions from your administrator\. If you cannot access a feature in Lambda, see [Troubleshooting AWS Lambda identity and access](security_iam_troubleshoot.md)\. - -**Service administrator** – If you're in charge of Lambda resources at your company, you probably have full access to Lambda\. It's your job to determine which Lambda features and resources your employees should access\. You must then submit requests to your IAM administrator to change the permissions of your service users\. Review the information on this page to understand the basic concepts of IAM\. To learn more about how your company can use IAM with Lambda, see [How AWS Lambda works with IAM](security_iam_service-with-iam.md)\. - -**IAM administrator** – If you're an IAM administrator, you might want to learn details about how you can write policies to manage access to Lambda\. To view example Lambda identity\-based policies that you can use in IAM, see [AWS Lambda identity\-based policy examples](security_iam_id-based-policy-examples.md)\. - -## Authenticating with identities - -Authentication is how you sign in to AWS using your identity credentials\. For more information about signing in using the AWS Management Console, see [The IAM Console and Sign\-in Page](https://docs.aws.amazon.com/IAM/latest/UserGuide/console.html) in the *IAM User Guide*\. - -You must be *authenticated* \(signed in to AWS\) as the AWS account root user, an IAM user, or by assuming an IAM role\. You can also use your company's single sign\-on authentication, or even sign in using Google or Facebook\. In these cases, your administrator previously set up identity federation using IAM roles\. When you access AWS using credentials from another company, you are assuming a role indirectly\. - -To sign in directly to the [AWS Management Console](https://console.aws.amazon.com/), use your password with your root user email or your IAM user name\. You can access AWS programmatically using your root user or IAM user access keys\. AWS provides SDK and command line tools to cryptographically sign your request using your credentials\. If you don’t use AWS tools, you must sign the request yourself\. Do this using *Signature Version 4*, a protocol for authenticating inbound API requests\. For more information about authenticating requests, see [Signature Version 4 Signing Process](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html) in the *AWS General Reference*\. - -Regardless of the authentication method that you use, you might also be required to provide additional security information\. For example, AWS recommends that you use multi\-factor authentication \(MFA\) to increase the security of your account\. To learn more, see [Using Multi\-Factor Authentication \(MFA\) in AWS](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa.html) in the *IAM User Guide*\. - -### AWS Account Root User - - When you first create an AWS account, you begin with a single sign\-in identity that has complete access to all AWS services and resources in the account\. This identity is called the AWS account *root user* and is accessed by signing in with the email address and password that you used to create the account\. We strongly recommend that you do not use the root user for your everyday tasks, even the administrative ones\. Instead, adhere to the [best practice of using the root user only to create your first IAM user](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#create-iam-users)\. Then securely lock away the root user credentials and use them to perform only a few account and service management tasks\. - -### IAM users and groups - -An *[IAM user](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html)* is an identity within your AWS account that has specific permissions for a single person or application\. An IAM user can have long\-term credentials such as a user name and password or a set of access keys\. To learn how to generate access keys, see [Managing Access Keys for IAM Users](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html) in the *IAM User Guide*\. When you generate access keys for an IAM user, make sure you view and securely save the key pair\. You cannot recover the secret access key in the future\. Instead, you must generate a new access key pair\. - -An [https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html) is an identity that specifies a collection of IAM users\. You can't sign in as a group\. You can use groups to specify permissions for multiple users at a time\. Groups make permissions easier to manage for large sets of users\. For example, you could have a group named *IAMAdmins* and give that group permissions to administer IAM resources\. - -Users are different from roles\. A user is uniquely associated with one person or application, but a role is intended to be assumable by anyone who needs it\. Users have permanent long\-term credentials, but roles provide temporary credentials\. To learn more, see [When to Create an IAM User \(Instead of a Role\)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id.html#id_which-to-choose) in the *IAM User Guide*\. - -### IAM roles - -An *[IAM role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html)* is an identity within your AWS account that has specific permissions\. It is similar to an IAM user, but is not associated with a specific person\. You can temporarily assume an IAM role in the AWS Management Console by [switching roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-console.html)\. You can assume a role by calling an AWS CLI or AWS API operation or by using a custom URL\. For more information about methods for using roles, see [Using IAM Roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html) in the *IAM User Guide*\. - -IAM roles with temporary credentials are useful in the following situations: -+ **Temporary IAM user permissions** – An IAM user can assume an IAM role to temporarily take on different permissions for a specific task\. -+ **Federated user access** – Instead of creating an IAM user, you can use existing identities from AWS Directory Service, your enterprise user directory, or a web identity provider\. These are known as *federated users*\. AWS assigns a role to a federated user when access is requested through an [identity provider](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers.html)\. For more information about federated users, see [Federated Users and Roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction_access-management.html#intro-access-roles) in the *IAM User Guide*\. -+ **Cross\-account access** – You can use an IAM role to allow someone \(a trusted principal\) in a different account to access resources in your account\. Roles are the primary way to grant cross\-account access\. However, with some AWS services, you can attach a policy directly to a resource \(instead of using a role as a proxy\)\. To learn the difference between roles and resource\-based policies for cross\-account access, see [How IAM Roles Differ from Resource\-based Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_compare-resource-policies.html) in the *IAM User Guide*\. -+ **AWS service access** – A service role is an IAM role that a service assumes to perform actions in your account on your behalf\. When you set up some AWS service environments, you must define a role for the service to assume\. This service role must include all the permissions that are required for the service to access the AWS resources that it needs\. Service roles vary from service to service, but many allow you to choose your permissions as long as you meet the documented requirements for that service\. Service roles provide access only within your account and cannot be used to grant access to services in other accounts\. You can create, modify, and delete a service role from within IAM\. For example, you can create a role that allows Amazon Redshift to access an Amazon S3 bucket on your behalf and then load data from that bucket into an Amazon Redshift cluster\. For more information, see [Creating a Role to Delegate Permissions to an AWS Service](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html) in the *IAM User Guide*\. -+ **Applications running on Amazon EC2** – You can use an IAM role to manage temporary credentials for applications that are running on an EC2 instance and making AWS CLI or AWS API requests\. This is preferable to storing access keys within the EC2 instance\. To assign an AWS role to an EC2 instance and make it available to all of its applications, you create an instance profile that is attached to the instance\. An instance profile contains the role and enables programs that are running on the EC2 instance to get temporary credentials\. For more information, see [Using an IAM Role to Grant Permissions to Applications Running on Amazon EC2 Instances](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2.html) in the *IAM User Guide*\. - -To learn whether to use IAM roles, see [When to Create an IAM Role \(Instead of a User\)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id.html#id_which-to-choose_role) in the *IAM User Guide*\. - -## Managing access using policies - -You control access in AWS by creating policies and attaching them to IAM identities or AWS resources\. A policy is an object in AWS that, when associated with an identity or resource, defines their permissions\. AWS evaluates these policies when an entity \(root user, IAM user, or IAM role\) makes a request\. Permissions in the policies determine whether the request is allowed or denied\. Most policies are stored in AWS as JSON documents\. For more information about the structure and contents of JSON policy documents, see [Overview of JSON Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#access_policies-json) in the *IAM User Guide*\. - -An IAM administrator can use policies to specify who has access to AWS resources, and what actions they can perform on those resources\. Every IAM entity \(user or role\) starts with no permissions\. In other words, by default, users can do nothing, not even change their own password\. To give a user permission to do something, an administrator must attach a permissions policy to a user\. Or the administrator can add the user to a group that has the intended permissions\. When an administrator gives permissions to a group, all users in that group are granted those permissions\. - -IAM policies define permissions for an action regardless of the method that you use to perform the operation\. For example, suppose that you have a policy that allows the `iam:GetRole` action\. A user with that policy can get role information from the AWS Management Console, the AWS CLI, or the AWS API\. - -### Identity\-based policies - -Identity\-based policies are JSON permissions policy documents that you can attach to an identity, such as an IAM user, role, or group\. These policies control what actions that identity can perform, on which resources, and under what conditions\. To learn how to create an identity\-based policy, see [Creating IAM Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html) in the *IAM User Guide*\. - -Identity\-based policies can be further categorized as *inline policies* or *managed policies*\. Inline policies are embedded directly into a single user, group, or role\. Managed policies are standalone policies that you can attach to multiple users, groups, and roles in your AWS account\. Managed policies include AWS managed policies and customer managed policies\. To learn how to choose between a managed policy or an inline policy, see [Choosing Between Managed Policies and Inline Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html#choosing-managed-or-inline) in the *IAM User Guide*\. - -### Resource\-based policies - -Resource\-based policies are JSON policy documents that you attach to a resource such as an Amazon S3 bucket\. Service administrators can use these policies to define what actions a specified principal \(account member, user, or role\) can perform on that resource and under what conditions\. Resource\-based policies are inline policies\. There are no managed resource\-based policies\. - -### Access control lists \(ACLs\) - -Access control lists \(ACLs\) are a type of policy that controls which principals \(account members, users, or roles\) have permissions to access a resource\. ACLs are similar to resource\-based policies, although they do not use the JSON policy document format\. Amazon S3, AWS WAF, and Amazon VPC are examples of services that support ACLs\. To learn more about ACLs, see [Access Control List \(ACL\) Overview](https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html) in the *Amazon Simple Storage Service Developer Guide*\. - -### Other policy types - -AWS supports additional, less\-common policy types\. These policy types can set the maximum permissions granted to you by the more common policy types\. -+ **Permissions boundaries** – A permissions boundary is an advanced feature in which you set the maximum permissions that an identity\-based policy can grant to an IAM entity \(IAM user or role\)\. You can set a permissions boundary for an entity\. The resulting permissions are the intersection of entity's identity\-based policies and its permissions boundaries\. Resource\-based policies that specify the user or role in the `Principal` field are not limited by the permissions boundary\. An explicit deny in any of these policies overrides the allow\. For more information about permissions boundaries, see [Permissions Boundaries for IAM Entities](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) in the *IAM User Guide*\. -+ **Service control policies \(SCPs\)** – SCPs are JSON policies that specify the maximum permissions for an organization or organizational unit \(OU\) in AWS Organizations\. AWS Organizations is a service for grouping and centrally managing multiple AWS accounts that your business owns\. If you enable all features in an organization, then you can apply service control policies \(SCPs\) to any or all of your accounts\. The SCP limits permissions for entities in member accounts, including each AWS account root user\. For more information about Organizations and SCPs, see [How SCPs Work](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_about-scps.html) in the *AWS Organizations User Guide*\. -+ **Session policies** – Session policies are advanced policies that you pass as a parameter when you programmatically create a temporary session for a role or federated user\. The resulting session's permissions are the intersection of the user or role's identity\-based policies and the session policies\. Permissions can also come from a resource\-based policy\. An explicit deny in any of these policies overrides the allow\. For more information, see [Session Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) in the *IAM User Guide*\. - -### Multiple policy types - -When multiple types of policies apply to a request, the resulting permissions are more complicated to understand\. To learn how AWS determines whether to allow a request when multiple policy types are involved, see [Policy Evaluation Logic](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html) in the *IAM User Guide*\. \ No newline at end of file diff --git a/doc_source/security-infrastructure.md b/doc_source/security-infrastructure.md deleted file mode 100644 index 00003eb3..00000000 --- a/doc_source/security-infrastructure.md +++ /dev/null @@ -1,7 +0,0 @@ -# Infrastructure security in AWS Lambda - -As a managed service, AWS Lambda is protected by the AWS global network security procedures that are described in the [Amazon Web Services: Overview of security processes](https://d0.awsstatic.com/whitepapers/Security/AWS_Security_Whitepaper.pdf) whitepaper\. - -You use AWS published API calls to access Lambda through the network\. Clients must support Transport Layer Security \(TLS\) 1\.0 or later\. We recommend TLS 1\.2 or later\. Clients must also support cipher suites with perfect forward secrecy \(PFS\) such as Ephemeral Diffie\-Hellman \(DHE\) or Elliptic Curve Ephemeral Diffie\-Hellman \(ECDHE\)\. Most modern systems such as Java 7 and later support these modes\. - -Additionally, requests must be signed by using an access key ID and a secret access key that is associated with an IAM principal\. Or you can use the [AWS Security Token Service](https://docs.aws.amazon.com/STS/latest/APIReference/Welcome.html) \(AWS STS\) to generate temporary security credentials to sign requests\. \ No newline at end of file diff --git a/doc_source/security-resilience.md b/doc_source/security-resilience.md deleted file mode 100644 index 20c6de33..00000000 --- a/doc_source/security-resilience.md +++ /dev/null @@ -1,13 +0,0 @@ -# Resilience in AWS Lambda - -The AWS global infrastructure is built around AWS Regions and Availability Zones\. AWS Regions provide multiple physically separated and isolated Availability Zones, which are connected with low\-latency, high\-throughput, and highly redundant networking\. With Availability Zones, you can design and operate applications and databases that automatically fail over between Availability Zones without interruption\. Availability Zones are more highly available, fault tolerant, and scalable than traditional single or multiple data center infrastructures\. - -For more information about AWS Regions and Availability Zones, see [AWS global infrastructure](http://aws.amazon.com/about-aws/global-infrastructure/)\. - -In addition to the AWS global infrastructure, Lambda offers several features to help support your data resiliency and backup needs\. -+ **Versioning** – You can use versioning in Lambda to save your function's code and configuration as you develop it\. Together with aliases, you can use versioning to perform blue/green and rolling deployments\. For details, see [AWS Lambda function versions](configuration-versions.md)\. -+ **Scaling** – When your function receives a request while it's processing a previous request, Lambda launches another instance of your function to handle the increased load\. Lambda automatically scales to handle 1,000 concurrent executions per Region, a [limit](gettingstarted-limits.md) that can be increased if needed\. For details, see [AWS Lambda function scaling](invocation-scaling.md)\. -+ **High availability** – Lambda runs your function in multiple Availability Zones to ensure that it is available to process events in case of a service interruption in a single zone\. If you configure your function to connect to a virtual private cloud \(VPC\) in your account, specify subnets in multiple Availability Zones to ensure high availability\. For details, see [Configuring a Lambda function to access resources in a VPC](configuration-vpc.md)\. -+ **Reserved concurrency** – To make sure that your function can always scale to handle additional requests, you can reserve concurrency for it\. Setting reserved concurrency for a function ensures that it can scale to, but not exceed, a specified number of concurrent invocations\. This ensures that you don't lose requests due to other functions consuming all of the available concurrency\. For details, see [Managing concurrency for a Lambda function](configuration-concurrency.md)\. -+ **Retries** – For asynchronous invocations and a subset of invocations triggered by other services, Lambda automatically retries on error with delays between retries\. Other clients and AWS services that invoke functions synchronously are responsible for performing retries\. For details, see [Error handling and automatic retries in AWS Lambda](invocation-retries.md)\. -+ **Dead\-letter queue** – For asynchronous invocations, you can configure Lambda to send requests to a dead\-letter queue if all retries fail\. A dead\-letter queue is an Amazon SNS topic or Amazon SQS queue that receives events for troubleshooting or reprocessing\. For details, see [AWS Lambda function dead\-letter queues](invocation-async.md#dlq)\. \ No newline at end of file diff --git a/doc_source/security_iam_id-based-policy-examples.md b/doc_source/security_iam_id-based-policy-examples.md deleted file mode 100644 index 78c66425..00000000 --- a/doc_source/security_iam_id-based-policy-examples.md +++ /dev/null @@ -1,63 +0,0 @@ -# AWS Lambda identity\-based policy examples - -By default, IAM users and roles don't have permission to create or modify Lambda resources\. They also can't perform tasks using the AWS Management Console, AWS CLI, or AWS API\. An IAM administrator must create IAM policies that grant users and roles permission to perform specific API operations on the specified resources they need\. The administrator must then attach those policies to the IAM users or groups that require those permissions\. - -To learn how to create an IAM identity\-based policy using these example JSON policy documents, see [Creating policies on the JSON tab](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html#access_policies_create-json-editor) in the *IAM User Guide*\. - -**Topics** -+ [Policy best practices](#security_iam_service-with-iam-policy-best-practices) -+ [Using the Lambda console](#security_iam_id-based-policy-examples-console) -+ [Allow users to view their own permissions](#security_iam_id-based-policy-examples-view-own-permissions) - -## Policy best practices - -Identity\-based policies are very powerful\. They determine whether someone can create, access, or delete Lambda resources in your account\. These actions can incur costs for your AWS account\. When you create or edit identity\-based policies, follow these guidelines and recommendations: -+ **Get Started Using AWS Managed Policies** – To start using Lambda quickly, use AWS managed policies to give your employees the permissions they need\. These policies are already available in your account and are maintained and updated by AWS\. For more information, see [Get Started Using Permissions With AWS Managed Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#bp-use-aws-defined-policies) in the *IAM User Guide*\. -+ **Grant Least Privilege** – When you create custom policies, grant only the permissions required to perform a task\. Start with a minimum set of permissions and grant additional permissions as necessary\. Doing so is more secure than starting with permissions that are too lenient and then trying to tighten them later\. For more information, see [Grant Least Privilege](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege) in the *IAM User Guide*\. -+ **Enable MFA for Sensitive Operations** – For extra security, require IAM users to use multi\-factor authentication \(MFA\) to access sensitive resources or API operations\. For more information, see [Using Multi\-Factor Authentication \(MFA\) in AWS](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa.html) in the *IAM User Guide*\. -+ **Use Policy Conditions for Extra Security** – To the extent that it's practical, define the conditions under which your identity\-based policies allow access to a resource\. For example, you can write conditions to specify a range of allowable IP addresses that a request must come from\. You can also write conditions to allow requests only within a specified date or time range, or to require the use of SSL or MFA\. For more information, see [IAM JSON Policy Elements: Condition](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html) in the *IAM User Guide*\. - -## Using the Lambda console - -To access the AWS Lambda console, you must have a minimum set of permissions\. These permissions must allow you to list and view details about the Lambda resources in your AWS account\. If you create an identity\-based policy that is more restrictive than the minimum required permissions, the console won't function as intended for entities \(IAM users or roles\) with that policy\. - -For an example policy that grants minimal access for function development, see [Function development](access-control-identity-based.md#permissions-user-function)\. In addition to Lambda APIs, the Lambda console uses other services to display trigger configuration and let you add new triggers\. If your users use Lambda with other services, they need access to those services as well\. For details on configuring other services with Lambda, see [Using AWS Lambda with other services](lambda-services.md)\. - -## Allow users to view their own permissions - -This example shows how you might create a policy that allows IAM users to view the inline and managed policies that are attached to their user identity\. This policy includes permissions to complete this action on the console or programmatically using the AWS CLI or AWS API\. - -``` -{ - "Version": "2012-10-17", - "Statement": [ - { - "Sid": "ViewOwnUserInfo", - "Effect": "Allow", - "Action": [ - "iam:GetUserPolicy", - "iam:ListGroupsForUser", - "iam:ListAttachedUserPolicies", - "iam:ListUserPolicies", - "iam:GetUser" - ], - "Resource": ["arn:aws:iam::*:user/${aws:username}"] - }, - { - "Sid": "NavigateInConsole", - "Effect": "Allow", - "Action": [ - "iam:GetGroupPolicy", - "iam:GetPolicyVersion", - "iam:GetPolicy", - "iam:ListAttachedGroupPolicies", - "iam:ListGroupPolicies", - "iam:ListPolicyVersions", - "iam:ListPolicies", - "iam:ListUsers" - ], - "Resource": "*" - } - ] -} -``` \ No newline at end of file diff --git a/doc_source/security_iam_service-with-iam.md b/doc_source/security_iam_service-with-iam.md deleted file mode 100644 index 661aec29..00000000 --- a/doc_source/security_iam_service-with-iam.md +++ /dev/null @@ -1,5 +0,0 @@ -# How AWS Lambda works with IAM - -Before you use IAM to manage access to Lambda, you should understand what IAM features are available to use with Lambda\. To get a high\-level view of how Lambda and other AWS services work with IAM, see [AWS services that work with IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-services-that-work-with-iam.html) in the *IAM User Guide*\. - -For an overview of permissions, policies, and roles as they are used by Lambda, see [AWS Lambda permissions](lambda-permissions.md)\. \ No newline at end of file diff --git a/doc_source/security_iam_troubleshoot.md b/doc_source/security_iam_troubleshoot.md deleted file mode 100644 index c0539d71..00000000 --- a/doc_source/security_iam_troubleshoot.md +++ /dev/null @@ -1,64 +0,0 @@ -# Troubleshooting AWS Lambda identity and access - -Use the following information to help you diagnose and fix common issues that you might encounter when working with Lambda and IAM\. - -**Topics** -+ [I am not authorized to perform an action in Lambda](#security_iam_troubleshoot-no-permissions) -+ [I am not authorized to perform iam:PassRole](#security_iam_troubleshoot-passrole) -+ [I want to view my access keys](#security_iam_troubleshoot-access-keys) -+ [I'm an administrator and want to allow others to access Lambda](#security_iam_troubleshoot-admin-delegate) -+ [I want to allow people outside of my AWS account to access my Lambda resources](#security_iam_troubleshoot-cross-account-access) - -## I am not authorized to perform an action in Lambda - -If the AWS Management Console tells you that you're not authorized to perform an action, then you must contact your administrator for assistance\. Your administrator is the person that provided you with your user name and password\. - -The following example error occurs when the `mateojackson` IAM user tries to use the console to view details about a function but does not have `lambda:GetFunction` permissions\. - -``` -User: arn:aws:iam::123456789012:user/mateojackson is not authorized to perform: lambda:GetFunction on resource: my-function -``` - -In this case, Mateo asks his administrator to update his policies to allow him to access the `my-function` resource using the `lambda:GetFunction` action\. - -## I am not authorized to perform iam:PassRole - -If you receive an error that you're not authorized to perform the `iam:PassRole` action, then you must contact your administrator for assistance\. Your administrator is the person that provided you with your user name and password\. Ask that person to update your policies to allow you to pass a role to Lambda\. - -Some AWS services allow you to pass an existing role to that service, instead of creating a new service role or service\-linked role\. To do this, you must have permissions to pass the role to the service\. - -The following example error occurs when an IAM user named `marymajor` tries to use the console to perform an action in Lambda\. However, the action requires the service to have permissions granted by a service role\. Mary does not have permissions to pass the role to the service\. - -``` -User: arn:aws:iam::123456789012:user/marymajor is not authorized to perform: iam:PassRole -``` - -In this case, Mary asks her administrator to update her policies to allow her to perform the `iam:PassRole` action\. - -## I want to view my access keys - -After you create your IAM user access keys, you can view your access key ID at any time\. However, you can't view your secret access key again\. If you lose your secret key, you must create a new access key pair\. - -Access keys consist of two parts: an access key ID \(for example, `AKIAIOSFODNN7EXAMPLE`\) and a secret access key \(for example, `wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY`\)\. Like a user name and password, you must use both the access key ID and secret access key together to authenticate your requests\. Manage your access keys as securely as you do your user name and password\. - -**Important** - Do not provide your access keys to a third party, even to help [find your canonical user ID](https://docs.aws.amazon.com/general/latest/gr/acct-identifiers.html#FindingCanonicalId)\. By doing this, you might give someone permanent access to your account\. - -When you create an access key pair, you are prompted to save the access key ID and secret access key in a secure location\. The secret access key is available only at the time you create it\. If you lose your secret access key, you must add new access keys to your IAM user\. You can have a maximum of two access keys\. If you already have two, you must delete one key pair before creating a new one\. To view instructions, see [Managing Access Keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html#Using_CreateAccessKey) in the *IAM User Guide*\. - -## I'm an administrator and want to allow others to access Lambda - -To allow others to access Lambda, you must create an IAM entity \(user or role\) for the person or application that needs access\. They will use the credentials for that entity to access AWS\. You must then attach a policy to the entity that grants them the correct permissions in Lambda\. - -To get started right away, see [Creating Your First IAM Delegated User and Group](https://docs.aws.amazon.com/IAM/latest/UserGuide/getting-started_create-delegated-user.html) in the *IAM User Guide*\. - -## I want to allow people outside of my AWS account to access my Lambda resources - -You can create a role that users in other accounts or people outside of your organization can use to access your resources\. You can specify who is trusted to assume the role\. For services that support resource\-based policies or access control lists \(ACLs\), you can use those policies to grant people access to your resources\. - -To learn more, consult the following: -+ To learn whether Lambda supports these features, see [How AWS Lambda works with IAM](security_iam_service-with-iam.md)\. -+ To learn how to provide access to your resources across AWS accounts that you own, see [Providing Access to an IAM User in Another AWS Account That You Own](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_common-scenarios_aws-accounts.html) in the *IAM User Guide*\. -+ To learn how to provide access to your resources to third\-party AWS accounts, see [Providing Access to AWS Accounts Owned by Third Parties](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_common-scenarios_third-party.html) in the *IAM User Guide*\. -+ To learn how to provide access through identity federation, see [Providing Access to Externally Authenticated Users \(Identity Federation\)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_common-scenarios_federated-users.html) in the *IAM User Guide*\. -+ To learn the difference between using roles and resource\-based policies for cross\-account access, see [How IAM Roles Differ from Resource\-based Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_compare-resource-policies.html) in the *IAM User Guide*\. \ No newline at end of file diff --git a/doc_source/services-alb.md b/doc_source/services-alb.md deleted file mode 100644 index 8281e205..00000000 --- a/doc_source/services-alb.md +++ /dev/null @@ -1,69 +0,0 @@ -# Using AWS Lambda with an Application Load Balancer - -You can use a Lambda function to process requests from an Application Load Balancer\. Elastic Load Balancing supports Lambda functions as a target for an Application Load Balancer\. Use load balancer rules to route HTTP requests to a function, based on path or header values\. Process the request and return an HTTP response from your Lambda function\. - -Elastic Load Balancing invokes your Lambda function synchronously with an event that contains the request body and metadata\. - -**Example Application Load Balancer request event** - -``` -{ - "requestContext": { - "elb": { - "targetGroupArn": "arn:aws:elasticloadbalancing:us-east-2:123456789012:targetgroup/lambda-279XGJDqGZ5rsrHC2Fjr/49e9d65c45c6791a" - } - }, - "httpMethod": "GET", - "path": "/lambda", - "queryStringParameters": { - "query": "1234ABCD" - }, - "headers": { - "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", - "accept-encoding": "gzip", - "accept-language": "en-US,en;q=0.9", - "connection": "keep-alive", - "host": "lambda-alb-123578498.us-east-2.elb.amazonaws.com", - "upgrade-insecure-requests": "1", - "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36", - "x-amzn-trace-id": "Root=1-5c536348-3d683b8b04734faae651f476", - "x-forwarded-for": "72.12.164.125", - "x-forwarded-port": "80", - "x-forwarded-proto": "http", - "x-imforwards": "20" - }, - "body": "", - "isBase64Encoded": false -} -``` - -Your function processes the event and returns a response document to the load balancer in JSON\. Elastic Load Balancing converts the document to an HTTP success or error response and returns it to the user\. - -**Example Response document format** - -``` -{ - "statusCode": 200, - "statusDescription": "200 OK", - "isBase64Encoded": False, - "headers": { - "Content-Type": "text/html" - }, - "body": "

Hello from Lambda!

" -} -``` - -To configure an Application Load Balancer as a function trigger, grant Elastic Load Balancing permission to execute the function, create a target group that routes requests to the function, and add a rule to the load balancer that sends requests to the target group\. - -Use the `add-permission` command to add a permission statement to your function's resource\-based policy\. - -``` -$ aws lambda add-permission --function-name alb-function \ ---statement-id load-balancer --action "lambda:InvokeFunction" \ ---principal elasticloadbalancing.amazonaws.com -{ - "Statement": "{\"Sid\":\"load-balancer\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"elasticloadbalancing.amazonaws.com\"},\"Action\":\"lambda:InvokeFunction\",\"Resource\":\"arn:aws:lambda:us-west-2:123456789012:function:alb-function\"}" -} -``` - -For instructions on configuring the Application Load Balancer listener and target group, see [Lambda functions as a target](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html) in the *User Guide for Application Load Balancers*\. \ No newline at end of file diff --git a/doc_source/services-alexa.md b/doc_source/services-alexa.md deleted file mode 100644 index 341b96f2..00000000 --- a/doc_source/services-alexa.md +++ /dev/null @@ -1,32 +0,0 @@ -# Using AWS Lambda with Alexa - -You can use Lambda functions to build services that give new skills to Alexa, the Voice assistant on Amazon Echo\. The Alexa Skills Kit provides the APIs, tools, and documentation to create these new skills, powered by your own services running as Lambda functions\. Amazon Echo users can access these new skills by asking Alexa questions or making requests\. - -The Alexa Skills Kit is available on GitHub\. -+ [Alexa Skills Kit SDK for Node\.js ](https://github.com/alexa/alexa-skills-kit-sdk-for-nodejs) -+ [Alexa Skills Kit SDK for Java](https://github.com/alexa/alexa-skills-kit-sdk-for-java) - -**Example Alexa smart home event** - -``` -{ - "header": { - "payloadVersion": "1", - "namespace": "Control", - "name": "SwitchOnOffRequest" - }, - "payload": { - "switchControlAction": "TURN_ON", - "appliance": { - "additionalApplianceDetails": { - "key2": "value2", - "key1": "value1" - }, - "applianceId": "sampleId" - }, - "accessToken": "sampleAccessToken" - } -} -``` - -For more information, see [Getting started with Alexa Skills Kit](https://developer.amazon.com/appsandservices/solutions/alexa/alexa-skills-kit/getting-started-guide)\. \ No newline at end of file diff --git a/doc_source/services-apigateway-blueprint.md b/doc_source/services-apigateway-blueprint.md deleted file mode 100644 index 2880d544..00000000 --- a/doc_source/services-apigateway-blueprint.md +++ /dev/null @@ -1,56 +0,0 @@ -# Create a simple microservice using Lambda and API Gateway - -In this tutorial you will use the Lambda console to create a Lambda function, and an Amazon API Gateway endpoint to trigger that function\. You will be able to call the endpoint with any method \(`GET`, `POST`, `PATCH`, etc\.\) to trigger your Lambda function\. When the endpoint is called, the entire request will be passed through to your Lambda function\. Your function action will depend on the method you call your endpoint with: -+ DELETE: delete an item from a DynamoDB table -+ GET: scan table and return all items -+ POST: Create an item -+ PUT: Update an item - -## Create an API using Amazon API Gateway - -Follow the steps in this section to create a new Lambda function and an API Gateway endpoint to trigger it: - -**To create an API** - -1. Sign in to the AWS Management Console and open the AWS Lambda console\. - -1. Choose **Create Lambda function**\. - -1. Choose **Blueprint**\. - -1. Enter **microservice** in the search bar\. Choose the **microservice\-http\-endpoint** blueprint and then choose **Configure**\. - -1. Configure the following settings\. - + **Name** – **lambda\-microservice**\. - + **Role** – **Create a new role from one or more templates**\. - + **Role name** – **lambda\-apigateway\-role**\. - + **Policy templates** – **Simple microservice permissions**\. - + **API** – **Create a new API**\. - + **Security** – **Open**\. - - Choose **Create function**\. - -When you complete the wizard and create your function, Lambda creates a proxy resource named `lambda-microservice` under the API name you selected\. For more information about proxy resources, see [Configure proxy integration for a proxy resource](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-set-up-simple-proxy.html)\. - -A proxy resource has an `AWS_PROXY` integration type and a catch\-all method `ANY`\. The `AWS_PROXY` integration type applies a default mapping template to pass through the entire request to the Lambda function and transforms the output from the Lambda function to HTTP responses\. The `ANY` method defines the same integration setup for all the supported methods, including `GET`, `POST`, `PATCH`, `DELETE `and others\. - -## Test sending an HTTPS request - -In this step, you will use the console to test the Lambda function\. In addition, you can run a `curl` command to test the end\-to\-end experience\. That is, send an HTTPS request to your API method and have Amazon API Gateway invoke your Lambda function\. In order to complete the steps, make sure you have created a DynamoDB table and named it "MyTable"\. For more information, see [Create a DynamoDB table with a stream enabled](with-ddb-example.md#with-ddb-create-buckets) - -**To test the API** - -1. With your `MyLambdaMicroService` function still open in the console, choose the **Actions** tab and then choose **Configure test event**\. - -1. Replace the existing text with the following: - - ``` - { - "httpMethod": "GET", - "queryStringParameters": { - "TableName": "MyTable" - } - } - ``` - -1. After entering the text above choose **Save and test**\. \ No newline at end of file diff --git a/doc_source/services-apigateway-code.md b/doc_source/services-apigateway-code.md deleted file mode 100644 index e5738b01..00000000 --- a/doc_source/services-apigateway-code.md +++ /dev/null @@ -1,140 +0,0 @@ -# Sample function code - -Sample code is available for the following languages\. - -**Topics** -+ [Node\.js](#services-apigateway-code-nodejs) -+ [Python 3](#services-apigateway-code-python) -+ [Go](#services-apigateway-code-go) - -## Node\.js - -The following example processes messages from API Gateway, and manages DynamoDB documents based on the request method\. - -**Example index\.js** - -``` -console.log('Loading function'); - -var AWS = require('aws-sdk'); -var dynamo = new AWS.DynamoDB.DocumentClient(); - -/** - * Provide an event that contains the following keys: - * - * - operation: one of the operations in the switch statement below - * - tableName: required for operations that interact with DynamoDB - * - payload: a parameter to pass to the operation being performed - */ -exports.handler = function(event, context, callback) { - //console.log('Received event:', JSON.stringify(event, null, 2)); - - var operation = event.operation; - - if (event.tableName) { - event.payload.TableName = event.tableName; - } - - switch (operation) { - case 'create': - dynamo.put(event.payload, callback); - break; - case 'read': - dynamo.get(event.payload, callback); - break; - case 'update': - dynamo.update(event.payload, callback); - break; - case 'delete': - dynamo.delete(event.payload, callback); - break; - case 'list': - dynamo.scan(event.payload, callback); - break; - case 'echo': - callback(null, "Success"); - break; - case 'ping': - callback(null, "pong"); - break; - default: - callback('Unknown operation: ${operation}'); - } -}; -``` - -Zip up the sample code to create a deployment package\. For instructions, see [AWS Lambda deployment package in Node\.js](nodejs-package.md)\. - -## Python 3 - -The following example processes messages from API Gateway, and manages DynamoDB documents based on the request method\. - -**Example LambdaFunctionOverHttps\.py** - -``` -from __future__ import print_function - -import boto3 -import json - -print('Loading function') - - -def handler(event, context): - '''Provide an event that contains the following keys: - - - operation: one of the operations in the operations dict below - - tableName: required for operations that interact with DynamoDB - - payload: a parameter to pass to the operation being performed - ''' - #print("Received event: " + json.dumps(event, indent=2)) - - operation = event['operation'] - - if 'tableName' in event: - dynamo = boto3.resource('dynamodb').Table(event['tableName']) - - operations = { - 'create': lambda x: dynamo.put_item(**x), - 'read': lambda x: dynamo.get_item(**x), - 'update': lambda x: dynamo.update_item(**x), - 'delete': lambda x: dynamo.delete_item(**x), - 'list': lambda x: dynamo.scan(**x), - 'echo': lambda x: x, - 'ping': lambda x: 'pong' - } - - if operation in operations: - return operations[operation](event.get('payload')) - else: - raise ValueError('Unrecognized operation "{}"'.format(operation)) -``` - -Zip up the sample code to create a deployment package\. For instructions, see [AWS Lambda deployment package in Python](python-package.md)\. - -## Go - -The following example processes messages from API Gateway, and logs information about the request\. - -**Example LambdaFunctionOverHttps\.go** - -``` -import ( - "strings" - "github.com/aws/aws-lambda-go/events" -) - -func handleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) { - fmt.Printf("Processing request data for request %s.\n", request.RequestContext.RequestId) - fmt.Printf("Body size = %d.\n", len(request.Body)) - - fmt.Println("Headers:") - for key, value := range request.Headers { - fmt.Printf(" %s: %s\n", key, value) - } - - return events.APIGatewayProxyResponse { Body: request.Body, StatusCode: 200 }, nil -} -``` - -Build the executable with `go build` and create a deployment package\. For instructions, see [AWS Lambda deployment package in Go](golang-package.md)\. \ No newline at end of file diff --git a/doc_source/services-apigateway-template.md b/doc_source/services-apigateway-template.md deleted file mode 100644 index e1218922..00000000 --- a/doc_source/services-apigateway-template.md +++ /dev/null @@ -1,25 +0,0 @@ -# AWS SAM template for an API Gateway application - -Below is a sample AWS SAM template for the Lambda application from the [tutorial](services-apigateway-tutorial.md)\. Copy the text below to a file and save it next to the ZIP package you created previously\. Note that the `Handler` and `Runtime` parameter values should match the ones you used when you created the function in the previous section\. - -**Example template\.yaml** - -``` -AWSTemplateFormatVersion: '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Resources: - LambdaFunctionOverHttps: - Type: AWS::Serverless::Function - Properties: - Handler: index.handler - Runtime: nodejs12.x - Policies: AmazonDynamoDBFullAccess - Events: - HttpPost: - Type: Api - Properties: - Path: '/DynamoDBOperations/DynamoDBManager' - Method: post -``` - -For information on how to package and deploy your serverless application using the package and deploy commands, see [Deploying serverless applications](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-deploying.html) in the *AWS Serverless Application Model Developer Guide*\. \ No newline at end of file diff --git a/doc_source/services-apigateway-tutorial.md b/doc_source/services-apigateway-tutorial.md deleted file mode 100644 index 6bb55460..00000000 --- a/doc_source/services-apigateway-tutorial.md +++ /dev/null @@ -1,476 +0,0 @@ -# Tutorial: Using AWS Lambda with Amazon API Gateway - -In this example you create a simple API using Amazon API Gateway\. An Amazon API Gateway is a collection of resources and methods\. For this tutorial, you create one resource \(`DynamoDBManager`\) and define one method \(`POST`\) on it\. The method is backed by a Lambda function \(`LambdaFunctionOverHttps`\)\. That is, when you call the API through an HTTPS endpoint, Amazon API Gateway invokes the Lambda function\. - -The `POST` method on the `DynamoDBManager` resource supports the following DynamoDB operations: -+ Create, update, and delete an item\. -+ Read an item\. -+ Scan an item\. -+ Other operations \(echo, ping\), not related to DynamoDB, that you can use for testing\. - -The request payload you send in the `POST` request identifies the DynamoDB operation and provides necessary data\. For example: -+ The following is a sample request payload for a DynamoDB create item operation: - - ``` - { - "operation": "create", - "tableName": "lambda-apigateway", - "payload": { - "Item": { - "id": "1", - "name": "Bob" - } - } - } - ``` -+ The following is a sample request payload for a DynamoDB read item operation: - - ``` - { - "operation": "read", - "tableName": "lambda-apigateway", - "payload": { - "Key": { - "id": "1" - } - } - } - ``` -+ The following is a sample request payload for an `echo` operation\. You send an HTTP POST request to the endpoint, using the following data in the request body\. - - ``` - { - "operation": "echo", - "payload": { - "somekey1": "somevalue1", - "somekey2": "somevalue2" - } - } - ``` - -**Note** -API Gateway offers advanced capabilities, such as: -**Pass through the entire request** – A Lambda function can receive the entire HTTP request \(instead of just the request body\) and set the HTTP response \(instead of just the response body\) using the `AWS_PROXY` integration type\. -**Catch\-all methods** – Map all methods of an API resource to a single Lambda function with a single mapping, using the `ANY` catch\-all method\. -**Catch\-all resources** – Map all sub\-paths of a resource to a Lambda function without any additional configuration using the new path parameter \(`{proxy+})`\. -To learn more about these API Gateway features, see [Configure proxy integration for a proxy resource](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-set-up-simple-proxy.html)\. - -## Prerequisites - -This tutorial assumes that you have some knowledge of basic Lambda operations and the Lambda console\. If you haven't already, follow the instructions in [Getting started with AWS Lambda](getting-started.md) to create your first Lambda function\. - -To follow the procedures in this guide, you will need a command line terminal or shell to run commands\. Commands are shown in listings preceded by a prompt symbol \($\) and the name of the current directory, when appropriate: - -``` -~/lambda-project$ this is a command -this is output -``` - -For long commands, an escape character \(`\`\) is used to split a command over multiple lines\. - -On Linux and macOS, use your preferred shell and package manager\. On Windows 10, you can [install the Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows\-integrated version of Ubuntu and Bash\. - -## Create the execution role - -Create the [execution role](lambda-intro-execution-role.md) that gives your function permission to access AWS resources\. - -**To create an execution role** - -1. Open the [roles page](https://console.aws.amazon.com/iam/home#/roles) in the IAM console\. - -1. Choose **Create role**\. - -1. Create a role with the following properties\. - + **Trusted entity** – Lambda\. - + **Role name** – **lambda\-apigateway\-role**\. - + **Permissions** – Custom policy with permission to DynamoDB and CloudWatch Logs\. - - ``` - { - "Version": "2012-10-17", - "Statement": [ - { - "Sid": "Stmt1428341300017", - "Action": [ - "dynamodb:DeleteItem", - "dynamodb:GetItem", - "dynamodb:PutItem", - "dynamodb:Query", - "dynamodb:Scan", - "dynamodb:UpdateItem" - ], - "Effect": "Allow", - "Resource": "*" - }, - { - "Sid": "", - "Resource": "*", - "Action": [ - "logs:CreateLogGroup", - "logs:CreateLogStream", - "logs:PutLogEvents" - ], - "Effect": "Allow" - } - ] - } - ``` - -The custom policy has the permissions that the function needs to write data to DynamoDB and upload logs\. Note the Amazon Resource Name \(ARN\) of the role for later use\. - -## Create the function - -The following example code receives a API Gateway event input and processes the messages that it contains\. For illustration, the code writes some of the incoming event data to CloudWatch Logs\. - -**Note** -For sample code in other languages, see [Sample function code](services-apigateway-code.md)\. - -**Example index\.js** - -``` -console.log('Loading function'); - -var AWS = require('aws-sdk'); -var dynamo = new AWS.DynamoDB.DocumentClient(); - -/** - * Provide an event that contains the following keys: - * - * - operation: one of the operations in the switch statement below - * - tableName: required for operations that interact with DynamoDB - * - payload: a parameter to pass to the operation being performed - */ -exports.handler = function(event, context, callback) { - //console.log('Received event:', JSON.stringify(event, null, 2)); - - var operation = event.operation; - - if (event.tableName) { - event.payload.TableName = event.tableName; - } - - switch (operation) { - case 'create': - dynamo.put(event.payload, callback); - break; - case 'read': - dynamo.get(event.payload, callback); - break; - case 'update': - dynamo.update(event.payload, callback); - break; - case 'delete': - dynamo.delete(event.payload, callback); - break; - case 'list': - dynamo.scan(event.payload, callback); - break; - case 'echo': - callback(null, "Success"); - break; - case 'ping': - callback(null, "pong"); - break; - default: - callback('Unknown operation: ${operation}'); - } -}; -``` - -**To create the function** - -1. Copy the sample code into a file named `index.js`\. - -1. Create a deployment package\. - - ``` - $ zip function.zip index.js - ``` - -1. Create a Lambda function with the `create-function` command\. - - ``` - $ aws lambda create-function --function-name LambdaFunctionOverHttps \ - --zip-file fileb://function.zip --handler index.handler --runtime nodejs12.x \ - --role arn:aws:iam::123456789012:role/service-role/lambda-apigateway-role - ``` - -## Test the Lambda function - -Invoke the function manually using the sample event data\. We recommend that you invoke the function using the console because the console UI provides a user\-friendly interface for reviewing the execution results, including the execution summary, logs written by your code, and the results returned by the function \(because the console always performs synchronous execution—invokes the Lambda function using the `RequestResponse` invocation type\)\. - -**To test the Lambda function** - -1. Copy the following JSON into a file and save it as `input.txt`\. - - ``` - { - "operation": "echo", - "payload": { - "somekey1": "somevalue1", - "somekey2": "somevalue2" - } - } - ``` - -1. Execute the following `invoke` command: - - ``` - $ aws lambda invoke --function-name LambdaFunctionOverHttps \ - --payload fileb://input.txt outputfile.txt - ``` - -## Create an API using Amazon API Gateway - -In this step, you associate your Lambda function with a method in the API that you created using Amazon API Gateway and test the end\-to\-end experience\. That is, when an HTTP request is sent to an API method, Amazon API Gateway invokes your Lambda function\. - -First, you create an API \(`DynamoDBOperations`\) using Amazon API Gateway with one resource \(`DynamoDBManager`\) and one method \(`POST`\)\. You associate the `POST` method with your Lambda function\. Then, you test the end\-to\-end experience\. - -### Create the API - -Run the following `create-rest-api` command to create the `DynamoDBOperations` API for this tutorial\. - -``` -$ aws apigateway create-rest-api --name DynamoDBOperations -{ - "id": "bs8fqo6bp0", - "name": "DynamoDBOperations", - "createdDate": 1539803980, - "apiKeySource": "HEADER", - "endpointConfiguration": { - "types": [ - "EDGE" - ] - } -} -``` - -Save the API ID for use in further commands\. You also need the ID of the API root resource\. To get the ID, run the `get-resources` command\. - -``` -$ API=bs8fqo6bp0 -$ aws apigateway get-resources --rest-api-id $API -{ - "items": [ - { - "path": "/", - "id": "e8kitthgdb" - } - ] -} -``` - -At this time you only have the root resource, but you add more resources in the next step\. - -### Create a resource in the API - -Run the following `create-resource` command to create a resource \(`DynamoDBManager`\) in the API that you created in the preceding section\. - -``` -$ aws apigateway create-resource --rest-api-id $API --path-part DynamoDBManager \ ---parent-id e8kitthgdb -{ - "path": "/DynamoDBManager", - "pathPart": "DynamoDBManager", - "id": "iuig5w", - "parentId": "e8kitthgdb" -} -``` - -Note the ID in the response\. This is the ID of the `DynamoDBManager` resource that you created\. - -### Create POST method on the resource - -Run the following `put-method` command to create a `POST` method on the `DynamoDBManager` resource in your API\. - -``` -$ RESOURCE=iuig5w -$ aws apigateway put-method --rest-api-id $API --resource-id $RESOURCE \ ---http-method POST --authorization-type NONE -{ - "apiKeyRequired": false, - "httpMethod": "POST", - "authorizationType": "NONE" -} -``` - -We specify `NONE` for the `--authorization-type` parameter, which means that unauthenticated requests for this method are supported\. This is fine for testing but in production you should use either the key\-based or role\-base authentication\. - -### Set the Lambda function as the destination for the POST method - -Run the following command to set the Lambda function as the integration point for the `POST` method\. This is the method Amazon API Gateway invokes when you make an HTTP request for the `POST` method endpoint\. This command and others use ARNs that include your account ID and region\. Save these to variables \(you can find your account ID in the role ARN that you used to create the function\)\. - -``` -$ REGION=us-east-2 -$ ACCOUNT=123456789012 -$ aws apigateway put-integration --rest-api-id $API --resource-id $RESOURCE \ ---http-method POST --type AWS --integration-http-method POST \ ---uri arn:aws:apigateway:$REGION:lambda:path/2015-03-31/functions/arn:aws:lambda:$REGION:$ACCOUNT:function:LambdaFunctionOverHttps/invocations -{ - "type": "AWS", - "httpMethod": "POST", - "uri": "arn:aws:apigateway:us-east-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-2:123456789012:function:LambdaFunctionOverHttps/invocations", - "passthroughBehavior": "WHEN_NO_MATCH", - "timeoutInMillis": 29000, - "cacheNamespace": "iuig5w", - "cacheKeyParameters": [] -} -``` - -`--integration-http-method` is the method that API Gateway uses to communicate with AWS Lambda\. `--uri` is unique identifier for the endpoint to which Amazon API Gateway can send request\. - -Set `content-type` of the `POST` method response and integration response to JSON as follows: -+ Run the following command to set the `POST` method response to JSON\. This is the response type that your API method returns\. - - ``` - $ aws apigateway put-method-response --rest-api-id $API \ - --resource-id $RESOURCE --http-method POST \ - --status-code 200 --response-models application/json=Empty - { - "statusCode": "200", - "responseModels": { - "application/json": "Empty" - } - } - ``` -+ Run the following command to set the `POST` method integration response to JSON\. This is the response type that Lambda function returns\. - - ``` - $ aws apigateway put-integration-response --rest-api-id $API \ - --resource-id $RESOURCE --http-method POST \ - --status-code 200 --response-templates application/json="" - { - "statusCode": "200", - "responseTemplates": { - "application/json": null - } - } - ``` - -### Deploy the API - -In this step, you deploy the API that you created to a stage called `prod`\. - -``` -$ aws apigateway create-deployment --rest-api-id $API --stage-name prod -{ - "id": "20vgsz", - "createdDate": 1539820012 -} -``` - -## Grant invoke permission to the API - -Now that you have an API created using Amazon API Gateway and you've deployed it, you can test\. First, you need to add permissions so that Amazon API Gateway can invoke your Lambda function when you send HTTP request to the `POST` method\. - -To do this, you need to add a permission to the permissions policy associated with your Lambda function\. Run the following `add-permission` AWS Lambda command to grant the Amazon API Gateway service principal \(`apigateway.amazonaws.com`\) permissions to invoke your Lambda function \(`LambdaFunctionOverHttps`\)\. - -``` -$ aws lambda add-permission --function-name LambdaFunctionOverHttps \ ---statement-id apigateway-test-2 --action lambda:InvokeFunction \ ---principal apigateway.amazonaws.com \ ---source-arn "arn:aws:execute-api:$REGION:$ACCOUNT:$API/*/POST/DynamoDBManager" -{ - "Statement": "{\"Sid\":\"apigateway-test-2\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"apigateway.amazonaws.com\"},\"Action\":\"lambda:InvokeFunction\",\"Resource\":\"arn:aws:lambda:us-east-2:123456789012:function:LambdaFunctionOverHttps\",\"Condition\":{\"ArnLike\":{\"AWS:SourceArn\":\"arn:aws:execute-api:us-east-2:123456789012:mnh1yprki7/*/POST/DynamoDBManager\"}}}" -} -``` - -You must grant this permission to enable testing \(if you go to the Amazon API Gateway and choose **Test** to test the API method, you need this permission\)\. Note the `--source-arn` specifies a wildcard character \(\*\) as the stage value \(indicates testing only\)\. This allows you to test without deploying the API\. - -**Note** -If your function and API are in different regions, the region identifier in the source ARN must match the region of the function, not the region of the API\. - -Now, run the same command again, but this time you grant to your deployed API permissions to invoke the Lambda function\. - -``` -$ aws lambda add-permission --function-name LambdaFunctionOverHttps \ ---statement-id apigateway-prod-2 --action lambda:InvokeFunction \ ---principal apigateway.amazonaws.com \ ---source-arn "arn:aws:execute-api:$REGION:$ACCOUNT:$API/prod/POST/DynamoDBManager" -{ - "Statement": "{\"Sid\":\"apigateway-prod-2\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"apigateway.amazonaws.com\"},\"Action\":\"lambda:InvokeFunction\",\"Resource\":\"arn:aws:lambda:us-east-2:123456789012:function:LambdaFunctionOverHttps\",\"Condition\":{\"ArnLike\":{\"AWS:SourceArn\":\"arn:aws:execute-api:us-east-2:123456789012:mnh1yprki7/prod/POST/DynamoDBManager\"}}}" -} -``` - -You grant this permission so that your deployed API has permissions to invoke the Lambda function\. Note that the `--source-arn` specifies a `prod` which is the stage name we used when deploying the API\. - -## Create a Amazon DynamoDB table - -Create the DynamoDB table that the Lambda function uses\. - -**To create a DynamoDB table** - -1. Open the [DynamoDB console](https://console.aws.amazon.com/dynamodb)\. - -1. Choose **Create table**\. - -1. Create a table with the following settings\. - + **Table name** – **lambda\-apigateway** - + **Primary key** – **id** \(string\) - -1. Choose **Create**\. - -## Trigger the function with an HTTP request - -In this step, you are ready to send an HTTP request to the `POST` method endpoint\. You can use either Curl or a method \(`test-invoke-method`\) provided by Amazon API Gateway\. - -You can use Amazon API Gateway CLI commands to send an HTTP `POST` request to the resource \(`DynamoDBManager`\) endpoint\. Because you deployed your Amazon API Gateway, you can use Curl to invoke the methods for the same operation\. - -The Lambda function supports using the `create` operation to create an item in your DynamoDB table\. To request this operation, use the following JSON: - -**Example create\-item\.json** - -``` -{ - "operation": "create", - "tableName": "lambda-apigateway", - "payload": { - "Item": { - "id": "1234ABCD", - "number": 5 - } - } -} -``` - -Save the test input to a file named `create-item.json`\. Run the `test-invoke-method` Amazon API Gateway command to send an HTTP `POST` method request to the resource \(`DynamoDBManager`\) endpoint\. - -``` -$ aws apigateway test-invoke-method --rest-api-id $API \ ---resource-id $RESOURCE --http-method POST --path-with-query-string "" \ ---body file://create-item.json -``` - -Or, you can use the following Curl command: - -``` -$ curl -X POST -d "{\"operation\":\"create\",\"tableName\":\"lambda-apigateway\",\"payload\":{\"Item\":{\"id\":\"1\",\"name\":\"Bob\"}}}" https://$API.execute-api.$REGION.amazonaws.com/prod/DynamoDBManager -``` - -To send request for the `echo` operation that your Lambda function supports, you can use the following request payload: - -**Example echo\.json** - -``` -{ - "operation": "echo", - "payload": { - "somekey1": "somevalue1", - "somekey2": "somevalue2" - } -} -``` - -Save the test input to a file named `echo.json`\. Run the `test-invoke-method` Amazon API Gateway CLI command to send an HTTP `POST` method request to the resource \(`DynamoDBManager`\) endpoint using the preceding JSON in the request body\. - -``` -$ aws apigateway test-invoke-method --rest-api-id $API \ ---resource-id $RESOURCE --http-method POST --path-with-query-string "" \ ---body file://echo.json -``` - -Or, you can use the following Curl command: - -``` -$ curl -X POST -d "{\"operation\":\"echo\",\"payload\":{\"somekey1\":\"somevalue1\",\"somekey2\":\"somevalue2\"}}" https://$API.execute-api.$REGION.amazonaws.com/prod/DynamoDBManager -``` \ No newline at end of file diff --git a/doc_source/services-apigateway.md b/doc_source/services-apigateway.md deleted file mode 100644 index dd000d69..00000000 --- a/doc_source/services-apigateway.md +++ /dev/null @@ -1,296 +0,0 @@ -# Using AWS Lambda with Amazon API Gateway - -You can create a web API with an HTTP endpoint for your Lambda function by using Amazon API Gateway\. API Gateway provides tools for creating and documenting web APIs that route HTTP requests to Lambda functions\. You can secure access to your API with authentication and authorization controls\. Your APIs can serve traffic over the internet or can be accessible only within your VPC\. - -**To add a public endpoint to your Lambda function** - -1. Open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions)\. - -1. Choose a function\. - -1. Under **Designer**, choose **Add trigger**\. - -1. Choose **API Gateway**\. - -1. For **API**, choose **Create an API**\. - -1. For **Security**, choose **Open**\. - -1. Choose **Add**\. - -With the **API Gateway** trigger selected in the designer, choose the endpoint to invoke the function with API Gateway\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/console-apig-endpoint.png) - -API Gateway APIs are comprised of stages, resources, methods, and integrations\. The stage and resource determine the path of the endpoint: - -**API path format** -+ `/prod/` – The `prod` stage and root resource\. -+ `/prod/user` – The `prod` stage and `user` resource\. -+ `/dev/{proxy+}` – Any route in the `dev` stage\. -+ `/` – \(HTTP APIs\) The default stage and root resource\. - -A Lambda integration maps a path and HTTP method combination to a Lambda function\. You can configure API Gateway to pass the body of the HTTP request as\-is \(custom integration\), or to encapsulate the request body in a document that includes all of the request information including headers, resource, path, and method\. - -Amazon API Gateway invokes your function [synchronously](invocation-sync.md) with an event that contains a JSON representation of the HTTP request\. For a custom integration, the event is the body of the request\. For a proxy integration, the event has a defined structure\. The following example shows a proxy event from an API Gateway REST API\. - -**Example [event\.json](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/nodejs-apig/event.json) API Gateway proxy event \(REST API\)** - -``` -{ - "resource": "/", - "path": "/", - "httpMethod": "GET", - "requestContext": { - "resourcePath": "/", - "httpMethod": "GET", - "path": "/Prod/", - ... - }, - "headers": { - "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", - "accept-encoding": "gzip, deflate, br", - "Host": "70ixmpl4fl.execute-api.us-east-2.amazonaws.com", - "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36", - "X-Amzn-Trace-Id": "Root=1-5e66d96f-7491f09xmpl79d18acf3d050", - ... - }, - "multiValueHeaders": { - "accept": [ - "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9" - ], - "accept-encoding": [ - "gzip, deflate, br" - ], - ... - }, - "queryStringParameters": null, - "multiValueQueryStringParameters": null, - "pathParameters": null, - "stageVariables": null, - "body": null, - "isBase64Encoded": false -} -``` - -This example shows an event for a GET request to the root path of the Prod stage of a REST API\. Event shape and contents vary by [API type](#services-apigateway-apitypes) and configuration\. - -API Gateway waits for a response from your function and relays the result to the caller\. For a custom integration, you define an integration response and a method response to convert the output from the function to an HTTP response\. For a proxy integration, the function must respond with a representation of the response in a specific format\. - -The following example shows a response object from a Node\.js function\. The response object represents a successful HTTP response that contains a JSON document\. - -**Example [index\.js](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/nodejs-apig/function/index.js) – Proxy integration response object \(Node\.js\)** - -``` -var response = { - "statusCode": 200, - "headers": { - "Content-Type": "application/json" - }, - "isBase64Encoded": false, - "multiValueHeaders": { - "X-Custom-Header": ["My value", "My other value"], - }, - "body": "{\n \"TotalCodeSize\": 104330022,\n \"FunctionCount\": 26\n}" - } -``` - -The Lambda runtime serializes the response object into JSON and sends it to the API\. The API parses the response and uses it to create an HTTP response, which it then sends to the client that made the original request\. - -**Example HTTP response** - -``` -< HTTP/1.1 200 OK -< Content-Type: application/json -< Content-Length: 55 -< Connection: keep-alive -< x-amzn-RequestId: 32998fea-xmpl-4268-8c72-16138d629356 -< X-Custom-Header: My value -< X-Custom-Header: My other value -< X-Amzn-Trace-Id: Root=1-5e6aa925-ccecxmplbae116148e52f036 -< -{ - "TotalCodeSize": 104330022, - "FunctionCount": 26 -} -``` - -Resources in your API define one or more methods, such as GET or POST\. Methods have an integration that routes requests to a Lambda function or another integration type\. You can define each resource and method individually, or use special resource and method types to match all requests that fit a pattern\. A *proxy resource* catches all paths beneath a resource\. The `ANY` method catches all HTTP methods\. - -**Topics** -+ [Permissions](#apigateway-permissions) -+ [Handling errors with an API Gateway API](#services-apigateway-errors) -+ [Choosing an API type](#services-apigateway-apitypes) -+ [Sample applications](#services-apigateway-samples) -+ [Tutorial: Using AWS Lambda with Amazon API Gateway](services-apigateway-tutorial.md) -+ [Sample function code](services-apigateway-code.md) -+ [Create a simple microservice using Lambda and API Gateway](services-apigateway-blueprint.md) -+ [AWS SAM template for an API Gateway application](services-apigateway-template.md) - -## Permissions - -Amazon API Gateway gets permission to invoke your function from the function's [resource\-based policy](access-control-resource-based.md)\. You can grant invoke permission to an entire API, or grant limited access to a stage, resource, or method\. - -When you add an API to your function by using the Lambda console, using the API Gateway console, or in an AWS SAM template, the function's resource\-based policy is updated automatically\. The following example shows a function policy with a statement that was added by an AWS SAM template\. - -**Example Function policy** - -``` -{ - "Version": "2012-10-17", - "Id": "default", - "Statement": [ - { - "Sid": "nodejs-apig-functiongetEndpointPermissionProd-BWDBXMPLXE2F", - "Effect": "Allow", - "Principal": { - "Service": "apigateway.amazonaws.com" - }, - "Action": "lambda:InvokeFunction", - "Resource": "arn:aws:lambda:us-east-2:123456789012:function:nodejs-apig-function-1G3MXMPLXVXYI", - "Condition": { - "ArnLike": { - "AWS:SourceArn": "arn:aws:execute-api:us-east-2:123456789012:ktyvxmpls1/*/GET/" - } - } - } - ] -} -``` - -[Confirm the function policy](access-control-resource-based.md) in the **Permissions** tab of the Lambda console\. - -You can manage function policy permissions manually with the following API operations: -+ [AddPermission](API_AddPermission.md) -+ [RemovePermission](API_RemovePermission.md) -+ [GetPolicy](API_GetPolicy.md) - -To grant invocation permission to an existing API, use the `add-permission` command\. - -``` -$ aws lambda add-permission --function-name my-function \ ---statement-id apigateway-get --action lambda:InvokeFunction \ ---principal apigateway.amazonaws.com \ ---source-arn "arn:aws:execute-api:us-east-2:123456789012:mnh1xmpli7/default/GET/" -{ - "Statement": "{\"Sid\":\"apigateway-test-2\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"apigateway.amazonaws.com\"},\"Action\":\"lambda:InvokeFunction\",\"Resource\":\"arn:aws:lambda:us-east-2:123456789012:function:my-function\",\"Condition\":{\"ArnLike\":{\"AWS:SourceArn\":\"arn:aws:execute-api:us-east-2:123456789012:mnh1xmpli7/default/GET\"}}}" -} -``` - -**Note** -If your function and API are in different regions, the region identifier in the source ARN must match the region of the function, not the region of the API\. When API Gateway invokes a function, it uses a resource ARN that is based on the ARN of the API, but modified to match the function's region\. - -The source ARN in this example grants permission to an integration on the GET method of the root resource in the default stage of an API, with ID `mnh1xmpli7`\. You can use an asterisk in the source ARN to grant permissions to multiple stages, methods, or resources\. - -**Resource patterns** -+ `mnh1xmpli7/*/GET/*` – GET method on all resources in all stages\. -+ `mnh1xmpli7/prod/ANY/user` – ANY method on the `user` resource in the `prod` stage\. -+ `mnh1xmpli7/*/*/*` – Any method on all resources in all stages\. - -For details on viewing the policy and removing statements, see [Cleaning up resource\-based policies](access-control-resource-based.md#permissions-resource-cleanup)\. - -## Handling errors with an API Gateway API - -API Gateway treats all invocation and function errors as internal errors\. If the Lambda API rejects the invocation request, API Gateway returns a 500 error code\. If the function runs but returns an error, or returns a response in the wrong format, API Gateway returns a 502\. In both cases, the body of the response from API Gateway is `{"message": "Internal server error"}`\. - -The following example shows an X\-Ray trace map for a request that resulted in a function error and a 502 from API Gateway\. The client receives the generic error message\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/tracemap-apig-502.png) - -To customize the error response, you must catch errors in your code and format a response in the required format\. - -**Example [index\.js](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/nodejs-apig/function/index.js) – Error formatting** - -``` -var formatError = function(error){ - var response = { - "statusCode": error.statusCode, - "headers": { - "Content-Type": "text/plain", - "x-amzn-ErrorType": error.code - }, - "isBase64Encoded": false, - "body": error.code + ": " + error.message - } - return response -} -``` - -API Gateway converts this response into an HTTP error with a custom status code and body\. In the trace map, the function node is green because it handled the error\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/tracemap-apig-404.png) - -## Choosing an API type - -API Gateway supports three types of APIs that invoke Lambda functions: -+ **HTTP API** – A lightweight, low\-latency RESTful API\. -+ **REST API** – A customizable, feature\-rich RESTful API\. -+ **WebSocket API** – A web API that maintains persistent connections with clients for full\-duplex communication\. - -HTTP APIs and REST APIs are both RESTful APIs that process HTTP requests and return responses\. HTTP APIs are newer and are built with the API Gateway version 2 API\. The following features are new for HTTP APIs: - -**HTTP API features** -+ **Automatic deployments** – When you modify routes or integrations, changes deploy automatically to stages that have automatic deployment enabled\. -+ **Default stage** – You can create a default stage \(`$default`\) to serve requests at the root path of your API's URL\. For named stages, you must include the stage name at the beginning of the path\. -+ **CORS configuration** – You can configure your API to add CORS headers to outgoing responses, instead of adding them manually in your function code\. - -REST APIs are the classic RESTful APIs that API Gateway has supported since launch\. REST APIs currently have more customization, integration, and management features\. - -**REST API features** -+ **Integration types** – REST APIs support custom Lambda integrations\. With a custom integration, you can send just the body of the request to the function, or apply a transform template to the request body before sending it to the function\. -+ **Access control** – REST APIs support more options for authentication and authorization\. -+ **Monitoring and tracing** – REST APIs support AWS X\-Ray tracing and additional logging options\. - -For a detailed comparison, see [Choosing between HTTP APIs and REST APIs](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-vs-rest.html) in the *API Gateway Developer Guide*\. - -WebSocket APIs also use the API Gateway version 2 API and support a similar feature set\. Use a WebSocket API for applications that benefit from a persistent connection between the client and API\. WebSocket APIs provide full\-duplex communication, which means that both the client and the API can send messages continuously without waiting for a response\. - -HTTP APIs support a simplified event format \(version 2\.0\)\. The following example shows an event from an HTTP API\. - -**Example [event\-v2\.json](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/nodejs-apig/event-v2.json) – API Gateway proxy event \(HTTP API\)** - -``` -{ - "version": "2.0", - "routeKey": "ANY /nodejs-apig-function-1G3XMPLZXVXYI", - "rawPath": "/default/nodejs-apig-function-1G3XMPLZXVXYI", - "rawQueryString": "", - "cookies": [ - "s_fid=7AABXMPL1AFD9BBF-0643XMPL09956DE2", - "regStatus=pre-register" - ], - "headers": { - "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", - "accept-encoding": "gzip, deflate, br", - ... - }, - "requestContext": { - "accountId": "123456789012", - "apiId": "r3pmxmplak", - "domainName": "r3pmxmplak.execute-api.us-east-2.amazonaws.com", - "domainPrefix": "r3pmxmplak", - "http": { - "method": "GET", - "path": "/default/nodejs-apig-function-1G3XMPLZXVXYI", - "protocol": "HTTP/1.1", - "sourceIp": "205.255.255.176", - "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36" - }, - "requestId": "JKJaXmPLvHcESHA=", - "routeKey": "ANY /nodejs-apig-function-1G3XMPLZXVXYI", - "stage": "default", - "time": "10/Mar/2020:05:16:23 +0000", - "timeEpoch": 1583817383220 - }, - "isBase64Encoded": true -} -``` - -For more information, see [AWS Lambda integrations](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html) in the API Gateway Developer Guide\. - -## Sample applications - -The GitHub repository for this guide provides the following sample application for API Gateway\. -+ [API Gateway with Node\.js](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/nodejs-apig) – A function with an AWS SAM template that creates a REST API that has AWS X\-Ray tracing enabled\. It includes scripts for deploying, invoking the function, testing the API, and cleanup\. - -Lambda also provides [blueprints](gettingstarted-features.md#gettingstarted-features-blueprints) and [templates](gettingstarted-features.md#gettingstarted-features-templates) that you can use to create an API Gateway application in the Lambda console\. \ No newline at end of file diff --git a/doc_source/services-cloudformation.md b/doc_source/services-cloudformation.md deleted file mode 100644 index 3f030830..00000000 --- a/doc_source/services-cloudformation.md +++ /dev/null @@ -1,102 +0,0 @@ -# Using AWS Lambda with AWS CloudFormation - -In an AWS CloudFormation template, you can specify a Lambda function as the target of a custom resource\. Use custom resources to process parameters, retrieve configuration values, or call other AWS services during stack lifecycle events\. - -The following example invokes a function that's defined elsewhere in the template\. - -**Example – Custom resource definition** - -``` -Resources: - primerinvoke: - Type: [AWS::CloudFormation::CustomResource](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cfn-customresource.html) - Version: "1.0" - Properties: - ServiceToken: !GetAtt primer.Arn - FunctionName: !Ref randomerror -``` - -The service token is the Amazon Resource Name \(ARN\) of the function that AWS CloudFormation invokes when you create, update, or delete the stack\. You can also include additional properties like `FunctionName`, which AWS CloudFormation passes to your function as is\. - -AWS CloudFormation invokes your Lambda function [asynchronously](invocation-async.md) with an event that includes a callback URL\. - -**Example – AWS CloudFormation message event** - -``` -{ - "RequestType": "Create", - "ServiceToken": "arn:aws:lambda:us-east-2:123456789012:function:lambda-error-processor-primer-14ROR2T3JKU66", - "ResponseURL": "https://cloudformation-custom-resource-response-useast2.s3-us-east-2.amazonaws.com/arn%3Aaws%3Acloudformation%3Aus-east-2%3A123456789012%3Astack/lambda-error-processor/1134083a-2608-1e91-9897-022501a2c456%7Cprimerinvoke%7C5d478078-13e9-baf0-464a-7ef285ecc786?AWSAccessKeyId=AKIAIOSFODNN7EXAMPLE&Expires=1555451971&Signature=28UijZePE5I4dvukKQqM%2F9Rf1o4%3D", - "StackId": "arn:aws:cloudformation:us-east-2:123456789012:stack/lambda-error-processor/1134083a-2608-1e91-9897-022501a2c456", - "RequestId": "5d478078-13e9-baf0-464a-7ef285ecc786", - "LogicalResourceId": "primerinvoke", - "ResourceType": "AWS::CloudFormation::CustomResource", - "ResourceProperties": { - "ServiceToken": "arn:aws:lambda:us-east-2:123456789012:function:lambda-error-processor-primer-14ROR2T3JKU66", - "FunctionName": "lambda-error-processor-randomerror-ZWUC391MQAJK" - } -} -``` - -The function is responsible for returning a response to the callback URL that indicates success or failure\. For the full response syntax, see [Custom resource response objects](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/crpg-ref-responses.html)\. - -**Example – AWS CloudFormation custom resource response** - -``` -{ - "Status": "SUCCESS", - "PhysicalResourceId": "2019/04/18/[$LATEST]b3d1bfc65f19ec610654e4d9b9de47a0", - "StackId": "arn:aws:cloudformation:us-east-2:123456789012:stack/lambda-error-processor/1134083a-2608-1e91-9897-022501a2c456", - "RequestId": "5d478078-13e9-baf0-464a-7ef285ecc786", - "LogicalResourceId": "primerinvoke" -} -``` - -AWS CloudFormation provides a library called `cfn-response` that handles sending the response\. If you define your function within a template, you can require the library by name\. AWS CloudFormation then adds the library to the deployment package that it creates for the function\. - -The following example function invokes a second function\. If the call succeeds, the function sends a success response to AWS CloudFormation, and the stack update continues\. The template uses the [AWS::Serverless::Function](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-function.html) resource type provided by AWS Serverless Application Model\. - -**Example [error\-processor/template\.yml](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/error-processor/template.yml) – Custom resource function** - -``` -Transform: 'AWS::Serverless-2016-10-31' -Resources: - primer: - Type: AWS::Serverless::Function - Properties: - Handler: index.handler - Runtime: nodejs12.x - InlineCode: | - var aws = require('aws-sdk'); - var response = require('cfn-response'); - exports.handler = function(event, context) { - // For Delete requests, immediately send a SUCCESS response. - if (event.RequestType == "Delete") { - response.send(event, context, "SUCCESS"); - return; - } - var responseStatus = "FAILED"; - var responseData = {}; - var functionName = event.ResourceProperties.FunctionName - var lambda = new aws.Lambda(); - lambda.invoke({ FunctionName: functionName }, function(err, invokeResult) { - if (err) { - responseData = {Error: "Invoke call failed"}; - console.log(responseData.Error + ":\n", err); - } - else responseStatus = "SUCCESS"; - response.send(event, context, responseStatus, responseData); - }); - }; - Description: Invoke a function to create a log stream. - MemorySize: 128 - Timeout: 8 - Role: !GetAtt role.Arn - Tracing: Active -``` - -If the function that the custom resource invokes isn't defined in a template, you can get the source code for `cfn-response` from [cfn\-response module](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-lambda-function-code-cfnresponsemodule.html) in the AWS CloudFormation User Guide\. - -For a sample application that uses a custom resource to ensure that a function's log group is created before another resource that depends on it, see [Error processor sample application for AWS Lambda](samples-errorprocessor.md)\. - -For more information about custom resources, see [Custom resources](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-custom-resources.html) in the *AWS CloudFormation User Guide*\. \ No newline at end of file diff --git a/doc_source/services-cloudwatchevents-expressions.md b/doc_source/services-cloudwatchevents-expressions.md deleted file mode 100644 index c8962962..00000000 --- a/doc_source/services-cloudwatchevents-expressions.md +++ /dev/null @@ -1,42 +0,0 @@ -# Schedule expressions using rate or cron - -AWS Lambda supports standard rate and cron expressions for frequencies of up to once per minute\. CloudWatch Events rate expressions have the following format\. - -``` -rate(Value Unit) -``` - -Where *Value* is a positive integer and *Unit* can be minute\(s\), hour\(s\), or day\(s\)\. For a singular value the unit must be singular \(for example, `rate(1 day)`\), otherwise plural \(for example, `rate(5 days)`\)\. - - -**Rate expression examples** - -| Frequency | Expression | -| --- | --- | -| Every 5 minutes | `rate(5 minutes)` | -| Every hour | `rate(1 hour)` | -| Every seven days | `rate(7 days)` | - -Cron expressions have the following format\. - -``` -cron(Minutes Hours Day-of-month Month Day-of-week Year) -``` - - -**Cron expression examples** - -| Frequency | Expression | -| --- | --- | -| 10:15 AM \(UTC\) every day | `cron(15 10 * * ? *)` | -| 6:00 PM Monday through Friday | `cron(0 18 ? * MON-FRI *)` | -| 8:00 AM on the first day of the month | `cron(0 8 1 * ? *)` | -| Every 10 min on weekdays | `cron(0/10 * ? * MON-FRI *)` | -| Every 5 minutes between 8:00 AM and 5:55 PM weekdays | `cron(0/5 8-17 ? * MON-FRI *)` | -| 9:00 AM on the first Monday of each month | `cron(0 9 ? * 2#1 *)` | - -Note the following: -+ If you are using the Lambda console, do not include the `cron` prefix to your expression\. -+ One of the day\-of\-month or day\-of\-week values must be a question mark \(`?`\)\. - -For more information, see [Schedule expressions for rules](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html) in the *CloudWatch Events User Guide*\. \ No newline at end of file diff --git a/doc_source/services-cloudwatchevents-tutorial.md b/doc_source/services-cloudwatchevents-tutorial.md deleted file mode 100644 index 0832d4c0..00000000 --- a/doc_source/services-cloudwatchevents-tutorial.md +++ /dev/null @@ -1,124 +0,0 @@ -# Tutorial: Using AWS Lambda with scheduled events - -In this tutorial, you do the following: -+ Create a Lambda function using the **lambda\-canary** blueprint\. You configure the Lambda function to run every minute\. Note that if the function returns an error, AWS Lambda logs error metrics to CloudWatch\. -+ Configure a CloudWatch alarm on the `Errors` metric of your Lambda function to post a message to your Amazon SNS topic when AWS Lambda emits error metrics to CloudWatch\. You subscribe to the Amazon SNS topics to get email notification\. In this tutorial, you do the following to set this up: - + Create an Amazon SNS topic\. - + Subscribe to the topic so you can get email notifications when a new message is posted to the topic\. - + In Amazon CloudWatch, set an alarm on the `Errors` metric of your Lambda function to publish a message to your SNS topic when errors occur\. - -## Prerequisites - -This tutorial assumes that you have some knowledge of basic Lambda operations and the Lambda console\. If you haven't already, follow the instructions in [Getting started with AWS Lambda](getting-started.md) to create your first Lambda function\. - -## Create a Lambda function - -1. Sign in to the AWS Management Console and open the AWS Lambda console at [https://console\.aws\.amazon\.com/lambda/](https://console.aws.amazon.com/lambda/)\. - -1. Choose **Create function**\. - -1. Choose **Blueprints**\. - -1. Enter **canary** in the search bar\. Choose the **lambda\-canary** blueprint, and then choose **Configure**\. - -1. Configure the following settings\. - + **Name** – **lambda\-canary**\. - + **Role** – **Create a new role from one or more templates**\. - + **Role name** – **lambda\-apigateway\-role**\. - + **Policy templates** – **Simple microservice permissions**\. - + **Rule** – **Create a new rule**\. - + **Rule name** – **CheckWebsiteScheduledEvent**\. - + **Rule description** – **CheckWebsiteScheduledEvent trigger**\. - + **Schedule expression** – **rate\(1 minute\)**\. - + **Enabled** – True \(checked\)\. - + **Environment variables** - + **site** – **https://docs\.aws\.amazon\.com/lambda/latest/dg/welcome\.html**\. - + **expected** – **What is AWS Lambda?**\. - -1. Choose **Create function**\. - -CloudWatch Events emits an event every minute, based on the schedule expression\. The event triggers the Lambda function, which verifies that the expected string appears in the specified page\. For more information on expressions schedules, see [Schedule expressions using rate or cron](services-cloudwatchevents-expressions.md)\. - -## Test the Lambda function - -Test the function with a sample event provided by the Lambda console\. - -1. Open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions)\. - -1. Choose **lambda\-canary**\. - -1. Next to the **Test** button at the top of the page, choose **Configure test events** from the drop\-down menu\. - -1. Create a new event using the **CloudWatch Events** event template\. - -1. Choose **Create**\. - -1. Choose **Test**\. - -The output from the function execution is shown at the top of the page\. - -## Create an Amazon SNS topic and subscribe to it - -Create an Amazon Simple Notification Service \(Amazon SNS\) topic to receive notifications when the canary function returns an error\. - -**To create a topic** - -1. Open the [Amazon SNS console](https://console.aws.amazon.com/sns/home)\. - -1. Choose **Create topic**\. - -1. Create a topic with the following settings\. - + **Name** – **lambda\-canary\-notifications**\. - + **Display name** – **Canary**\. - -1. Choose **Create subscription**\. - -1. Create a subscription with the following settings\. - + **Protocol** – **Email**\. - + **Endpoint** – Your email address\. - -Amazon SNS sends an email from `Canary `, reflecting the friendly name of the topic\. Use the link in the email to confirm your address\. - -## Configure an alarm - -Configure an alarm in Amazon CloudWatch that monitors the Lambda function and sends a notification when it fails\. - -**To create an alarm** - -1. Open the [CloudWatch console](https://console.aws.amazon.com/cloudwatch)\. - -1. Choose **Alarms**\. - -1. Choose **Create alarm**\. - -1. Choose **Alarms**\. - -1. Create an alarm with the following settings\. - + **Metrics** – **lambda\-canary Errors**\. - - Search for **lambda canary errors** to find the metric\. - + Statistic – **Sum**\. - - Choose the statistic from the drop\-down menu above the preview graph\. - + **Name** – **lambda\-canary\-alarm**\. - + **Description** – **Lambda canary alarm**\. - + Threshold – **Whenever Errors is >=****1**\. - + **Send notification to** – **lambda\-canary\-notifications**\. - -## Test the alarm - -Update the function configuration to cause the function to return an error, which triggers the alarm\. - -**To trigger an alarm** - -1. Open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions)\. - -1. Choose **lambda\-canary**\. - -1. Under **Environment variables**, choose **Edit**\. - -1. Set **expected** to **404**\. - -1. Choose **Save**\. - -Wait a minute, and then check your email for a message from Amazon SNS\. diff --git a/doc_source/services-cloudwatchevents.md b/doc_source/services-cloudwatchevents.md deleted file mode 100644 index 75bdda70..00000000 --- a/doc_source/services-cloudwatchevents.md +++ /dev/null @@ -1,74 +0,0 @@ -# Using AWS Lambda with Amazon CloudWatch Events - -[Amazon CloudWatch events](https://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/WhatIsCloudWatchEvents.html) help you to respond to state changes in your AWS resources\. When your resources change state, they automatically send events into an event stream\. You can create rules that match selected events in the stream and route them to your AWS Lambda function to take action\. For example, you can automatically invoke an AWS Lambda function to log the state of an [EC2 instance](https://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/LogEC2InstanceState.html) or [AutoScaling group](https://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/LogASGroupState.html)\. - -CloudWatch Events invokes your function asynchronously with an event document that wraps the event from its source\. The following example shows an event that originated from a database snapshot in Amazon Relational Database Service\. - -**Example CloudWatch Events event** - -``` -{ - "version": "0", - "id": "fe8d3c65-xmpl-c5c3-2c87-81584709a377", - "detail-type": "RDS DB Instance Event", - "source": "aws.rds", - "account": "123456789012", - "time": "2020-04-28T07:20:20Z", - "region": "us-east-2", - "resources": [ - "arn:aws:rds:us-east-2:123456789012:db:rdz6xmpliljlb1" - ], - "detail": { - "EventCategories": [ - "backup" - ], - "SourceType": "DB_INSTANCE", - "SourceArn": "arn:aws:rds:us-east-2:123456789012:db:rdz6xmpliljlb1", - "Date": "2020-04-28T07:20:20.112Z", - "Message": "Finished DB Instance backup", - "SourceIdentifier": "rdz6xmpliljlb1" - } -} -``` - -You can also create a Lambda function and direct AWS Lambda to execute it on a regular schedule\. You can specify a fixed rate \(for example, execute a Lambda function every hour or 15 minutes\), or you can specify a Cron expression\. - -**Example CloudWatch Events message event** - -``` -{ - "account": "123456789012", - "region": "us-east-2", - "detail": {}, - "detail-type": "Scheduled Event", - "source": "aws.events", - "time": "2019-03-01T01:23:45Z", - "id": "cdc73f9d-aea9-11e3-9d5a-835b769c0d9c", - "resources": [ - "arn:aws:events:us-east-1:123456789012:rule/my-schedule" - ] -} -``` - -**To configure CloudWatch Events to invoke your function** - -1. Open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions)\. - -1. Choose a function - -1. Under **Designer**, choose **Add trigger**\. - -1. Set the trigger type to **CloudWatch Events/EventBridge**\. - -1. For **Rule**, choose **Create a new rule**\. - -1. Configure the remaining options and choose **Add**\. - -For more information on expressions schedules, see [Schedule expressions using rate or cron](services-cloudwatchevents-expressions.md)\. - -Each AWS account can have up to 100 unique event sources of the **CloudWatch Events\- Schedule** source type\. Each of these can be the event source for up to five Lambda functions\. That is, you can have up to 500 Lambda functions that can be executing on a schedule in your AWS account\. - -**Topics** -+ [Tutorial: Using AWS Lambda with scheduled events](services-cloudwatchevents-tutorial.md) -+ [AWS SAM template for a CloudWatch Events application](with-scheduledevents-example-use-app-spec.md) -+ [Schedule expressions using rate or cron](services-cloudwatchevents-expressions.md) \ No newline at end of file diff --git a/doc_source/services-cloudwatchlogs.md b/doc_source/services-cloudwatchlogs.md deleted file mode 100644 index fb6d9739..00000000 --- a/doc_source/services-cloudwatchlogs.md +++ /dev/null @@ -1,40 +0,0 @@ -# Using AWS Lambda with Amazon CloudWatch Logs - -You can use a Lambda function to monitor and analyze logs from an Amazon CloudWatch Logs log stream\. Create [subscriptions](https://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/Subscriptions.html) for one or more log streams to invoke a function when logs are created or match an optional pattern\. Use the function to send a notification or persist the log to a database or storage\. - -CloudWatch Logs invokes your function asynchronously with an event that contains log data\. The value of the data field is a Base64 encoded ZIP archive\. - -**Example Amazon CloudWatch Logs message event** - -``` -{ - "awslogs": { - "data": "ewogICAgIm1lc3NhZ2VUeXBlIjogIkRBVEFfTUVTU0FHRSIsCiAgICAib3duZXIiOiAiMTIzNDU2Nzg5MDEyIiwKICAgICJsb2dHcm91cCI6I..." - } -} -``` - -When decoded and decompressed, the log data is a JSON document with the following structure\. - -**Example Amazon CloudWatch Logs message data \(decoded\)** - -``` -{ - "messageType": "DATA_MESSAGE", - "owner": "123456789012", - "logGroup": "/aws/lambda/echo-nodejs", - "logStream": "2019/03/13/[$LATEST]94fa867e5374431291a7fc14e2f56ae7", - "subscriptionFilters": [ - "LambdaStream_cloudwatchlogs-node" - ], - "logEvents": [ - { - "id": "34622316099697884706540976068822859012661220141643892546", - "timestamp": 1552518348220, - "message": "REPORT RequestId: 6234bffe-149a-b642-81ff-2e8e376d8aff\tDuration: 46.84 ms\tBilled Duration: 100 ms \tMemory Size: 192 MB\tMax Memory Used: 72 MB\t\n" - } - ] -} -``` - -For a sample application that uses CloudWatch Logs as a trigger, see [Error processor sample application for AWS Lambda](samples-errorprocessor.md)\. \ No newline at end of file diff --git a/doc_source/services-codecommit.md b/doc_source/services-codecommit.md deleted file mode 100644 index 2373fd8b..00000000 --- a/doc_source/services-codecommit.md +++ /dev/null @@ -1,36 +0,0 @@ -# Using AWS Lambda with AWS CodeCommit - -You can create a trigger for an AWS CodeCommit repository so that events in the repository will invoke a Lambda function\. For example, you can invoke a Lambda function when a branch or tag is created or when a push is made to an existing branch\. - -**Example AWS CodeCommit message event** - -``` -{ - "Records": [ - { - "awsRegion": "us-east-2", - "codecommit": { - "references": [ - { - "commit": "5e493c6f3067653f3d04eca608b4901eb227078", - "ref": "refs/heads/master" - } - ] - }, - "eventId": "31ade2c7-f889-47c5-a937-1cf99e2790e9", - "eventName": "ReferenceChanges", - "eventPartNumber": 1, - "eventSource": "aws:codecommit", - "eventSourceARN": "arn:aws:codecommit:us-east-2:123456789012:lambda-pipeline-repo", - "eventTime": "2019-03-12T20:58:25.400+0000", - "eventTotalParts": 1, - "eventTriggerConfigId": "0d17d6a4-efeb-46f3-b3ab-a63741badeb8", - "eventTriggerName": "index.handler", - "eventVersion": "1.0", - "userIdentityARN": "arn:aws:iam::123456789012:user/intern" - } - ] -} -``` - -For more information, see [Manage triggers for an AWS CodeCommit repository](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-notify.html)\. \ No newline at end of file diff --git a/doc_source/services-codepipeline.md b/doc_source/services-codepipeline.md deleted file mode 100644 index 9bc8fe94..00000000 --- a/doc_source/services-codepipeline.md +++ /dev/null @@ -1,96 +0,0 @@ -# Using AWS Lambda with AWS CodePipeline - -AWS CodePipeline is a service that enables you to create continuous delivery pipelines for applications that run on AWS\. You can create a pipeline to deploy your Lambda application\. You can also configure a pipeline to invoke a Lambda function to perform a task when the pipeline runs\. When you [create a Lambda application](deploying-lambda-apps.md) in the Lambda console, Lambda creates a pipeline that includes source, build, and deploy stages\. - -CodePipeline invokes your function asynchronously with an event that contains details about the job\. The following example shows an event from a pipeline that invoked a function named `my-function`\. - -**Example CodePipeline event** - -``` -{ - "CodePipeline.job": { - "id": "c0d76431-b0e7-xmpl-97e3-e8ee786eb6f6", - "accountId": "123456789012", - "data": { - "actionConfiguration": { - "configuration": { - "FunctionName": "my-function", - "UserParameters": "{\"KEY\": \"VALUE\"}" - } - }, - "inputArtifacts": [ - { - "name": "my-pipeline-SourceArtifact", - "revision": "e0c7xmpl2308ca3071aa7bab414de234ab52eea", - "location": { - "type": "S3", - "s3Location": { - "bucketName": "aws-us-west-2-123456789012-my-pipeline", - "objectKey": "my-pipeline/test-api-2/TdOSFRV" - } - } - } - ], - "outputArtifacts": [ - { - "name": "invokeOutput", - "revision": null, - "location": { - "type": "S3", - "s3Location": { - "bucketName": "aws-us-west-2-123456789012-my-pipeline", - "objectKey": "my-pipeline/invokeOutp/D0YHsJn" - } - } - } - ], - "artifactCredentials": { - "accessKeyId": "AKIAIOSFODNN7EXAMPLE", - "secretAccessKey": "6CGtmAa3lzWtV7a...", - "sessionToken": "IQoJb3JpZ2luX2VjEA...", - "expirationTime": 1575493418000 - } - } - } -} -``` - -To complete the job, the function must call the CodePipeline API to signal success or failure\. The following example Node\.js function uses the `PutJobSuccessResult` operation to signal success\. It gets the job ID for the API call from the event object\. - -**Example index\.js** - -``` -var AWS = require('aws-sdk') -var codepipeline = new AWS.CodePipeline() - -exports.handler = async (event) => { - console.log(JSON.stringify(event, null, 2)) - var jobId = event["CodePipeline.job"].id - var params = { - jobId: jobId - } - return codepipeline.putJobSuccessResult(params).promise() -} -``` - -For asynchronous invocation, Lambda queues the message and [retries](invocation-retries.md) if your function returns an error\. Configure your function with a [destination](invocation-async.md#invocation-async-destinations) to retain events that your function could not process\. - -For details on configuring a pipeline to invoke a Lambda function, see [Invoke an AWS Lambda function in a pipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/actions-invoke-lambda-function.html) in the AWS CodePipeline User Guide\. - -**Topics** -+ [Permissions](#services-codepipeline-permissions) -+ [Building a continuous delivery pipeline for a Lambda application with AWS CodePipeline](build-pipeline.md) - -## Permissions - -To invoke a function, a CodePipeline pipeline needs permission to use the following API operations: -+ [ListFunctions](API_ListFunctions.md) -+ [InvokeFunction](API_Invoke.md) - -The default [pipeline service role](https://docs.aws.amazon.com/codepipeline/latest/userguide/how-to-custom-role.html) includes these permissions\. - -To complete a job, the function needs the following permissions in its [execution role](lambda-intro-execution-role.md)\. -+ `codepipeline:PutJobSuccessResult` -+ `codepipeline:PutJobFailureResult` - -These permissions are included in the [AWSCodePipelineCustomActionAccess](https://console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/AWSCodePipelineCustomActionAccess) managed policy\. \ No newline at end of file diff --git a/doc_source/services-cognito.md b/doc_source/services-cognito.md deleted file mode 100644 index 36138928..00000000 --- a/doc_source/services-cognito.md +++ /dev/null @@ -1,30 +0,0 @@ -# Using AWS Lambda with Amazon Cognito - -The Amazon Cognito Events feature enables you to run Lambda functions in response to events in Amazon Cognito\. For example, you can invoke a Lambda function for the Sync Trigger events, that is published each time a dataset is synchronized\. To learn more and walk through an example, see [Introducing Amazon Cognito Events: Sync Triggers](https://aws.amazon.com/blogs/mobile/introducing-amazon-cognito-events-sync-triggers/) in the Mobile Development blog\. - -**Example Amazon Cognito message event** - -``` -{ - "datasetName": "datasetName", - "eventType": "SyncTrigger", - "region": "us-east-1", - "identityId": "identityId", - "datasetRecords": { - "SampleKey2": { - "newValue": "newValue2", - "oldValue": "oldValue2", - "op": "replace" - }, - "SampleKey1": { - "newValue": "newValue1", - "oldValue": "oldValue1", - "op": "replace" - } - }, - "identityPoolId": "identityPoolId", - "version": 2 -} -``` - -You configure event source mapping using Amazon Cognito event subscription configuration\. For information about event source mapping and a sample event, see [Amazon Cognito events](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-events.html) in the *Amazon Cognito Developer Guide*\. \ No newline at end of file diff --git a/doc_source/services-config.md b/doc_source/services-config.md deleted file mode 100644 index e1dfc5ea..00000000 --- a/doc_source/services-config.md +++ /dev/null @@ -1,22 +0,0 @@ -# Using AWS Lambda with AWS Config - -You can use AWS Lambda functions to evaluate whether your AWS resource configurations comply with your custom Config rules\. As resources are created, deleted, or changed, AWS Config records these changes and sends the information to your Lambda functions\. Your Lambda functions then evaluate the changes and report results to AWS Config\. You can then use AWS Config to assess overall resource compliance: you can learn which resources are noncompliant and which configuration attributes are the cause of noncompliance\. - -**Example AWS Config message event** - -``` -{ - "invokingEvent": "{\"configurationItem\":{\"configurationItemCaptureTime\":\"2016-02-17T01:36:34.043Z\",\"awsAccountId\":\"000000000000\",\"configurationItemStatus\":\"OK\",\"resourceId\":\"i-00000000\",\"ARN\":\"arn:aws:ec2:us-east-1:000000000000:instance/i-00000000\",\"awsRegion\":\"us-east-1\",\"availabilityZone\":\"us-east-1a\",\"resourceType\":\"AWS::EC2::Instance\",\"tags\":{\"Foo\":\"Bar\"},\"relationships\":[{\"resourceId\":\"eipalloc-00000000\",\"resourceType\":\"AWS::EC2::EIP\",\"name\":\"Is attached to ElasticIp\"}],\"configuration\":{\"foo\":\"bar\"}},\"messageType\":\"ConfigurationItemChangeNotification\"}", - "ruleParameters": "{\"myParameterKey\":\"myParameterValue\"}", - "resultToken": "myResultToken", - "eventLeftScope": false, - "executionRoleArn": "arn:aws:iam::012345678912:role/config-role", - "configRuleArn": "arn:aws:config:us-east-1:012345678912:config-rule/config-rule-0123456", - "configRuleName": "change-triggered-config-rule", - "configRuleId": "config-rule-0123456", - "accountId": "012345678912", - "version": "1.0" -} -``` - -For more information, see [Evaluating resources with AWS Config rules](https://docs.aws.amazon.com/config/latest/developerguide/evaluate-config.html)\. \ No newline at end of file diff --git a/doc_source/services-ec2-tutorial.md b/doc_source/services-ec2-tutorial.md deleted file mode 100644 index 72666469..00000000 --- a/doc_source/services-ec2-tutorial.md +++ /dev/null @@ -1,290 +0,0 @@ -# Tutorial: Using AWS SDK for \.NET to manage Amazon EC2 Spot Instances - -You can use the AWS SDK for \.NET to manage Amazon EC2 spot instances with C\# code\. The SDK enables you to use the Amazon EC2 API to create spot instance requests, determine when the request is fulfilled, delete requests, and identify the instances created\. - -This tutorial provides code that performs these tasks and a sample application that you can run locally or on AWS\. It includes a sample project that you can deploy to AWS Lambda's \.NET Core 2\.1 runtime\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/sample-ec2spot.png) - -For more information about spot instances usage and best practices, see [Spot Instances](https://docs.aws.amazon.com/AWSEC2/latest/DeveloperGuide/using-spot-instances.html) in the Amazon EC2 user guide\. - -## Prerequisites - -To follow the procedures in this guide, you will need a command line terminal or shell to run commands\. Commands are shown in listings preceded by a prompt symbol \($\) and the name of the current directory, when appropriate: - -``` -~/lambda-project$ this is a command -this is output -``` - -For long commands, an escape character \(`\`\) is used to split a command over multiple lines\. - -On Linux and macOS, use your preferred shell and package manager\. On Windows 10, you can [install the Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows\-integrated version of Ubuntu and Bash\. - -This tutorial uses code from the developer guide's GitHub repository\. The repository also contains helper scripts and configuration files that are needed to follow its procedures\. Clone the repository at [github\.com/awsdocs/aws\-lambda\-developer\-guide](https://github.com/awsdocs/aws-lambda-developer-guide)\. - -To use the sample code you need the following tools: -+ **AWS CLI** – To deploy the sample application to AWS, install the [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html)\. The AWS CLI also provides credentials to the sample code when you run it locally\. -+ **\.NET Core CLI** – To run and test the code locally, install the [\.NET Core SDK 2\.1](https://dotnet.microsoft.com/download/dotnet-core/2.1)\. -+ **Lambda \.NET Core Global Tool** – To build the deployment package for Lambda, install the [\.NET Core global tool](https://dotnet.microsoft.com/download/dotnet-core/2.1) with the \.NET Core CLI\. - - ``` - $ dotnet tool install -g [Amazon\.Lambda\.Tools](https://www.nuget.org/packages/Amazon.Lambda.Tools) - ``` - -The code in this tutorial manages spot requests that launch Amazon EC2 instances\. To run the code locally, you need SDK credentials with permission to use the following APIs\. -+ `ec2:RequestSpotInstance` -+ `ec2:GetSpotRequestState` -+ `ec2:CancelSpotRequest` -+ `ec2:TerminateInstances` - -To run the sample application in AWS, you need [permission to use Lambda](lambda-permissions.md) and the following services\. -+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html) \([pricing](https://aws.amazon.com/cloudformation/pricing/)\) -+ [Amazon Elastic Compute Cloud](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-policies-for-amazon-ec2.html) \([pricing](https://aws.amazon.com/ec2/pricing/)\) - -Standard charges apply for each service\. - -## Review the code - -Locate the sample project in the guide repository under [sample\-apps/ec2\-spot](https://github.com/awsdocs/aws-lambda-developer-guide/tree/master/sample-apps/ec2-spot)\. This directory contains Lambda function code, tests, project files, scripts, and a AWS CloudFormation template\. - -The `Function` class includes a `FunctionHandler` method that calls other methods to create spot requests, check their status, and clean up\. It creates an Amazon EC2 client with the AWS SDK for \.NET in a static constructor to allow it to be used throughout the class\. - -**Example [Function\.cs – FunctionHandler](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/ec2-spot/src/ec2spot/Function.cs#L17)** - -``` -using Amazon.EC2; -... - public class Function - { - private static AmazonEC2Client ec2Client; - - static Function() { - AWSSDKHandler.RegisterXRayForAllServices(); - ec2Client = new AmazonEC2Client(); - } - - public async Task FunctionHandler(Dictionary input, ILambdaContext context) - { - // More AMI IDs: [aws\.amazon\.com/amazon\-linux\-2/release\-notes/](https://aws.amazon.com/amazon-linux-2/release-notes/) - // us-east-2 HVM EBS-Backed 64-bit Amazon Linux 2 - string ami = "ami-09d9edae5eb90d556"; - string sg = "default"; - [InstanceType](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TInstanceType.html) type = InstanceType.T3aNano; - string price = "0.003"; - int count = 1; - var requestSpotInstances = await RequestSpotInstance(ami, sg, type, price, count); - var spotRequestId = requestSpotInstances.SpotInstanceRequests[0].SpotInstanceRequestId; -``` - -The `RequestSpotInstance` method creates a spot instance request\. - -**Example [Function\.cs – RequestSpotInstance](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/ec2-spot/src/ec2spot/Function.cs#L59)** - -``` -using Amazon; -using Amazon.Util; -using Amazon.EC2; -using Amazon.EC2.Model; -... - public async Task RequestSpotInstance( - string amiId, - string securityGroupName, - InstanceType instanceType, - string spotPrice, - int instanceCount) - { - var request = new RequestSpotInstancesRequest(); - - var launchSpecification = new [LaunchSpecification](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotLaunchSpecification.html)(); - launchSpecification.ImageId = amiId; - launchSpecification.InstanceType = instanceType; - launchSpecification.SecurityGroups.Add(securityGroupName); - - request.SpotPrice = spotPrice; - request.InstanceCount = instanceCount; - request.LaunchSpecification = launchSpecification; - - RequestSpotInstancesResponse response = await ec2Client.RequestSpotInstancesAsync(request); - - return response; - } -... -``` - -Next, you need to wait until the spot request reaches the `Active` state before proceeding to the last step\. To determine the state of your spot request, use the [DescribeSpotInstanceRequests](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TDescribeSpotInstanceRequestsRequest.html) method to obtain the state of the spot request ID to monitor\. - -``` -public async Task GetSpotRequest(string spotRequestId) -{ - var request = new DescribeSpotInstanceRequestsRequest(); - request.SpotInstanceRequestIds.Add(spotRequestId); - - var describeResponse = await ec2Client.DescribeSpotInstanceRequestsAsync(request); - - return describeResponse.SpotInstanceRequests[0]; -} -``` - -The final step is to clean up your requests and instances\. It is important to both cancel any outstanding requests and terminate any instances\. Just canceling your requests will not terminate your instances, which means that you will continue to be charged for them\. If you terminate your instances, your Spot requests may be canceled, but there are some scenarios, such as if you use persistent requests, where terminating your instances is not sufficient to stop your request from being re\-fulfilled\. Therefore, it is a best practice to both cancel any active requests and terminate any running instances\. - -You use the [CancelSpotInstanceRequests](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/MEC2CancelSpotInstanceRequestsCancelSpotInstanceRequestsRequest.html) method to cancel a Spot request\. The following example demonstrates how to cancel a Spot request\. - -``` -public async Task CancelSpotRequest(string spotRequestId) -{ - Console.WriteLine("Canceling request " + spotRequestId); - var cancelRequest = new CancelSpotInstanceRequestsRequest(); - cancelRequest.SpotInstanceRequestIds.Add(spotRequestId); - - await ec2Client.CancelSpotInstanceRequestsAsync(cancelRequest); -} -``` - -You use the [TerminateInstances](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/MEC2TerminateInstancesTerminateInstancesRequest.html) method to terminate an instance\. - -``` -public async Task TerminateSpotInstance(string instanceId) -{ - Console.WriteLine("Terminating instance " + instanceId); - var terminateRequest = new TerminateInstancesRequest(); - terminateRequest.InstanceIds = new List() { instanceId }; - try - { - var terminateResponse = await ec2Client.TerminateInstancesAsync(terminateRequest); - } - catch (AmazonEC2Exception ex) - { - // Check the ErrorCode to see if the instance does not exist. - if ("InvalidInstanceID.NotFound" == ex.ErrorCode) - { - Console.WriteLine("Instance {0} does not exist.", instanceId); - } - else - { - // The exception was thrown for another reason, so re-throw the exception. - throw; - } - } -} -``` - -## Run the code locally - -Run the code on your local machine to create a spot instance request\. After the request is fulfilled, the code deletes the request and terminates the instance\. - -**To run the application code** - -1. Navigate to the `ec2Spot.Tests` directory\. - - ``` - $ cd test/ec2Spot.Tests - ``` - -1. Use the \.NET CLI to run the project's unit tests\. - - ``` - test/ec2Spot.Tests$ dotnet test - Starting test execution, please wait... - sir-x5tgs5ij - open - open - open - open - open - active - Canceling request sir-x5tgs5ij - Terminating instance i-0b3fdff0e12e0897e - Complete - - Test Run Successful. - Total tests: 1 - Passed: 1 - Total time: 7.6060 Seconds - ``` - -The unit test invokes the FunctionHandler method to create a spot instance request, monitor it, and clean up\. It is implemented in the [xUnit\.net](https://xunit.net/) testing framework\. - -## Deploy the application - -Run the code in Lambda as a starting point for creating a serverless application\. - -**To deploy and test the application** - -1. Set your region to `us-east-2`\. - - ``` - $ export AWS_DEFAULT_REGION=us-east-2 - ``` - -1. Create a bucket for deployment artifacts\. - - ``` - $ ./create-bucket.sh - make_bucket: lambda-artifacts-63d5cbbf18fa5ecc - ``` - -1. Create a deployment package and deploy the application\. - - ``` - $ ./deploy.sh - Amazon Lambda Tools for .NET Core applications (3.3.0) - Project Home: https://github.com/aws/aws-extensions-for-dotnet-cli, https://github.com/aws/aws-lambda-dotnet - - Executing publish command - ... - Created publish archive (ec2spot.zip) - Lambda project successfully packaged: ec2spot.zip - Uploading to ebd38e401cedd7d676d05d22b76f0209 1305107 / 1305107.0 (100.00%) - Successfully packaged artifacts and wrote output template to file out.yaml. - Execute the following command to deploy the packaged template - aws cloudformation deploy --template-file out.yaml --stack-name - - Waiting for changeset to be created.. - Waiting for stack create/update to complete - Successfully created/updated stack - ec2-spot - ``` - -1. Open the [Applications page](https://us-east-2.console.aws.amazon.com/lambda/home?region=us-east-2#/applications/ec2-spot) of the Lambda console\. -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/sample-ec2spot-application.png) - -1. Under **Resources**, choose **function**\. - -1. Choose **Test** and create a test event from the default template\. - -1. Choose **Test** again to invoke the function\. - -View the logs and trace information to see the spot request ID and sequence of calls to Amazon EC2\. - -To view the service map, open the [Service map page](https://console.aws.amazon.com/xray/home#/service-map) in the X\-Ray console\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/sample-ec2spot-servicemap.png) - -Choose a node in the service map and then choose **View traces** to see a list of traces\. Choose a trace from the list to see the timeline of calls that the function made to Amazon EC2\. - -![\[\]](http://docs.aws.amazon.com/lambda/latest/dg/images/sample-ec2spot-timeline.png) - -## Clean up - -The code provided in this tutorial is designed to create and delete spot instance requests, and to terminate the instances that they launch\. However, if an error occurs, the requests and instances might not be cleaned up automatically\. View the spot requests and instances in the Amazon EC2 console\. - -**To confirm that Amazon EC2 resources are cleaned up** - -1. Open the [Spot Requests page](https://console.aws.amazon.com/ec2sp/v1/spot/home) in the Amazon EC2 console\. - -1. Verify that the state of the requests is **Cancelled**\. - -1. Choose the instance ID in the **Capacity** column to view the instance\. - -1. Verify that the state of the instances is **Terminated** or **Shutting down**\. - -To clean up the sample function and support resources, delete its AWS CloudFormation stack and the artifacts bucket that you created\. - -``` -$ ./cleanup.sh -Delete deployment artifacts and bucket (lambda-artifacts-63d5cbbf18fa5ecc)?y -delete: s3://lambda-artifacts-63d5cbbf18fa5ecc/ebd38e401cedd7d676d05d22b76f0209 -remove_bucket: lambda-artifacts-63d5cbbf18fa5ecc -``` - -The function's log group is not deleted automatically\. You can delete it in the [CloudWatch Logs console](https://console.aws.amazon.com/cloudwatch/home#logs:)\. Traces in X\-Ray expire after a few weeks and are deleted automatically\. \ No newline at end of file diff --git a/doc_source/services-ec2.md b/doc_source/services-ec2.md deleted file mode 100644 index d06de2a5..00000000 --- a/doc_source/services-ec2.md +++ /dev/null @@ -1,62 +0,0 @@ -# Using AWS Lambda with Amazon EC2 - -You can use AWS Lambda to process lifecycle events from Amazon Elastic Compute Cloud and manage Amazon EC2 resources\. Amazon EC2 sends events to Amazon CloudWatch Events for lifecycle events such as when an instance changes state, when an Amazon Elastic Block Store volume snapshot completes, or when a spot instance is scheduled to be terminated\. You configure CloudWatch Events to forward those events to a Lambda function for processing\. - -CloudWatch Events invokes your Lambda function asynchronously with the event document from Amazon EC2\. - -**Example Instance lifecycle event** - -``` -{ - "version": "0", - "id": "b6ba298a-7732-2226-xmpl-976312c1a050", - "detail-type": "EC2 Instance State-change Notification", - "source": "aws.ec2", - "account": "123456798012", - "time": "2019-10-02T17:59:30Z", - "region": "us-east-2", - "resources": [ - "arn:aws:ec2:us-east-2:123456798012:instance/i-0c314xmplcd5b8173" - ], - "detail": { - "instance-id": "i-0c314xmplcd5b8173", - "state": "running" - } -} -``` - -For details on configuring events in CloudWatch Events, see [Using AWS Lambda with Amazon CloudWatch Events](services-cloudwatchevents.md)\. For an example function that processes Amazon EBS snapshot notifications, see [Amazon CloudWatch Events for Amazon EBS](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-cloud-watch-events.html) in the Amazon EC2 User Guide for Linux Instances\. - -You can also use the AWS SDK to manage instances and other resources with the Amazon EC2 API\. For a tutorial with a sample application in C\#, see [Tutorial: Using AWS SDK for \.NET to manage Amazon EC2 Spot Instances](services-ec2-tutorial.md)\. - -## Permissions - -To process lifecycle events from Amazon EC2, CloudWatch Events needs permission to invoke your function\. This permission comes from the function's [resource\-based policy](access-control-resource-based.md)\. If you use the CloudWatch Events console to configure an event trigger, the console updates the resource\-based policy on your behalf\. Otherwise, add a statement like the following: - -**Example Resource\-based policy statement for Amazon EC2 lifecycle notifications** - -``` -{ - "Sid": "ec2-events", - "Effect": "Allow", - "Principal": { - "Service": "events.amazonaws.com" - }, - "Action": "lambda:InvokeFunction", - "Resource": "arn:aws:lambda:us-east-2:12456789012:function:my-function", - "Condition": { - "ArnLike": { - "AWS:SourceArn": "arn:aws:events:us-east-2:12456789012:rule/*" - } - } -} -``` - -To add a statement, use the `add-permission` AWS CLI command\. - -``` -aws lambda add-permission --action lambda:InvokeFunction --statement-id ec2-events \ ---principal events.amazonaws.com --function-name my-function --source-arn 'arn:aws:events:us-east-2:12456789012:rule/*' -``` - -If your function uses the AWS SDK to manage Amazon EC2 resources, add Amazon EC2 permissions to the function's [execution role](lambda-intro-execution-role.md)\. \ No newline at end of file diff --git a/doc_source/services-elasticache-tutorial.md b/doc_source/services-elasticache-tutorial.md deleted file mode 100644 index 07ccbebf..00000000 --- a/doc_source/services-elasticache-tutorial.md +++ /dev/null @@ -1,134 +0,0 @@ -# Tutorial: Configuring a Lambda function to access Amazon ElastiCache in an Amazon VPC - -In this tutorial, you do the following: -+ Create an Amazon ElastiCache cluster in your default Amazon Virtual Private Cloud\. For more information about Amazon ElastiCache, see [Amazon ElastiCache](https://aws.amazon.com/elasticache/)\. -+ Create a Lambda function to access the ElastiCache cluster\. When you create the Lambda function, you provide subnet IDs in your Amazon VPC and a VPC security group to allow the Lambda function to access resources in your VPC\. For illustration in this tutorial, the Lambda function generates a UUID, writes it to the cache, and retrieves it from the cache\. -+ Invoke the Lambda function and verify that it accessed the ElastiCache cluster in your VPC\. - -For details on using Lambda with Amazon VPC, see [Configuring a Lambda function to access resources in a VPC](configuration-vpc.md)\. - -## Prerequisites - -This tutorial assumes that you have some knowledge of basic Lambda operations and the Lambda console\. If you haven't already, follow the instructions in [Getting started with AWS Lambda](getting-started.md) to create your first Lambda function\. - -To follow the procedures in this guide, you will need a command line terminal or shell to run commands\. Commands are shown in listings preceded by a prompt symbol \($\) and the name of the current directory, when appropriate: - -``` -~/lambda-project$ this is a command -this is output -``` - -For long commands, an escape character \(`\`\) is used to split a command over multiple lines\. - -On Linux and macOS, use your preferred shell and package manager\. On Windows 10, you can [install the Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows\-integrated version of Ubuntu and Bash\. - -## Create the execution role - -Create the [execution role](lambda-intro-execution-role.md) that gives your function permission to access AWS resources\. - -**To create an execution role** - -1. Open the [roles page](https://console.aws.amazon.com/iam/home#/roles) in the IAM console\. - -1. Choose **Create role**\. - -1. Create a role with the following properties\. - + **Trusted entity** – Lambda\. - + **Permissions** – **AWSLambdaVPCAccessExecutionRole**\. - + **Role name** – **lambda\-vpc\-role**\. - -The **AWSLambdaVPCAccessExecutionRole** has the permissions that the function needs to manage network connections to a VPC\. - -## Create an ElastiCache cluster - -Create an ElastiCache cluster in your default VPC\. - -1. Run the following AWS CLI command to create a Memcached cluster\. - - ``` - $ aws elasticache create-cache-cluster --cache-cluster-id ClusterForLambdaTest \ - --cache-node-type cache.m3.medium --engine memcached --num-cache-nodes 1 \ - --security-group-ids sg-0897d5f549934c2fb - ``` - - You can look up the default VPC security group in the VPC console under **Security Groups**\. Your example Lambda function will add and retrieve an item from this cluster\. - -1. Write down the configuration endpoint for the cache cluster that you launched\. You can get this from the Amazon ElastiCache console\. You will specify this value in your Lambda function code in the next section\. - -## Create a deployment package - -The following example Python code reads and writes an item to your ElastiCache cluster\. - -**Example app\.py** - -``` -from __future__ import print_function -import time -import uuid -import sys -import socket -import elasticache_auto_discovery -from pymemcache.client.hash import HashClient - -#elasticache settings -elasticache_config_endpoint = "your-elasticache-cluster-endpoint:port" -nodes = elasticache_auto_discovery.discover(elasticache_config_endpoint) -nodes = map(lambda x: (x[1], int(x[2])), nodes) -memcache_client = HashClient(nodes) - -def handler(event, context): - """ - This function puts into memcache and get from it. - Memcache is hosted using elasticache - """ - - #Create a random UUID... this will be the sample element we add to the cache. - uuid_inserted = uuid.uuid4().hex - #Put the UUID to the cache. - memcache_client.set('uuid', uuid_inserted) - #Get item (UUID) from the cache. - uuid_obtained = memcache_client.get('uuid') - if uuid_obtained.decode("utf-8") == uuid_inserted: - # this print should go to the CloudWatch Logs and Lambda console. - print ("Success: Fetched value %s from memcache" %(uuid_inserted)) - else: - raise Exception("Value is not the same as we put :(. Expected %s got %s" %(uuid_inserted, uuid_obtained)) - - return "Fetched value from memcache: " + uuid_obtained.decode("utf-8") -``` - -**Dependencies** -+ [pymemcache](https://pypi.python.org/pypi/pymemcache) – The Lambda function code uses this library to create a `HashClient` object to set and get items from memcache\. -+ [elasticache\-auto\-discovery](https://pypi.python.org/pypi/elasticache-auto-discovery) – The Lambda function uses this library to get the nodes in your Amazon ElastiCache cluster\. - -Install dependencies with Pip and create a deployment package\. For instructions, see [AWS Lambda deployment package in Python](python-package.md)\. - -## Create the Lambda function - -Create the Lambda function with the `create-function` command\. - -``` -$ aws lambda create-function --function-name AccessMemCache --timeout 30 --memory-size 1024 \ ---zip-file fileb://function.zip --handler app.handler --runtime python3.8 \ ---role arn:aws:iam::123456789012:role/lambda-vpc-role \ ---vpc-config SubnetIds=subnet-0532bb6758ce7c71f,subnet-d6b7fda068036e11f,SecurityGroupIds=sg-0897d5f549934c2fb -``` - -You can find the subnet IDs and the default security group ID of your VPC from the VPC console\. - -## Test the Lambda function - -In this step, you invoke the Lambda function manually using the `invoke` command\. When the Lambda function executes, it generates a UUID and writes it to the ElastiCache cluster that you specified in your Lambda code\. The Lambda function then retrieves the item from the cache\. - -1. Invoke the Lambda function with the `invoke` command\. - - ``` - $ aws lambda invoke --function-name AccessMemCache output.txt - ``` - -1. Verify that the Lambda function executed successfully as follows: - + Review the output\.txt file\. - + Review the results in the AWS Lambda console\. - + Verify the results in CloudWatch Logs\. - -Now that you have created a Lambda function that accesses an ElastiCache cluster in your VPC, you can have the function invoked in response to events\. For information about configuring event sources and examples, see [Using AWS Lambda with other services](lambda-services.md)\. \ No newline at end of file diff --git a/doc_source/services-iot.md b/doc_source/services-iot.md deleted file mode 100644 index 0ba37cca..00000000 --- a/doc_source/services-iot.md +++ /dev/null @@ -1,33 +0,0 @@ -# Using AWS Lambda with AWS IoT - -AWS IoT provides secure communication between internet\-connected devices \(such as sensors\) and the AWS Cloud\. This makes it possible for you to collect, store, and analyze telemetry data from multiple devices\. - -You can create AWS IoT rules for your devices to interact with AWS services\. The AWS IoT [Rules Engine](https://docs.aws.amazon.com/iot/latest/developerguide/iot-rules.html) provides a SQL\-based language to select data from message payloads and send the data to other services, such as Amazon S3, Amazon DynamoDB, and AWS Lambda\. You define a rule to invoke a Lambda function when you want to invoke another AWS service or a third\-party service\. - -When an incoming IoT message triggers the rule, AWS IoT invokes your Lambda function [asynchronously](invocation-async.md) and passes data from the IoT message to the function\. - -The following example shows a moisture reading from a greenhouse sensor\. The **row** and **pos** values identify the location of the sensor\. This example event is based on the greenhouse type in the [AWS IoT Rules tutorials](https://docs.aws.amazon.com/iot/latest/developerguide/iot-rules-tutorial.html)\. - -**Example Example AWS IoT message event** - -``` -{ - "row" : "10", - "pos" : "23", - "moisture" : "75" -} -``` - -For asynchronous invocation, Lambda queues the message and [retries](invocation-retries.md) if your function returns an error\. Configure your function with a [destination](invocation-async.md#invocation-async-destinations) to retain events that your function could not process\. - -You need to grant permission for the AWS IoT service to invoke your Lambda function\. Use the `add-permission` command to add a permission statement to your function's resource\-based policy\. - -``` -$ aws lambda add-permission --function-name my-function \ ---statement-id iot-events --action "lambda:InvokeFunction" --principal iotevents.amazonaws.com -{ - "Statement": "{\"Sid\":\"iot-events\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"iot.amazonaws.com\"},\"Action\":\"lambda:InvokeFunction\",\"Resource\":\"arn:aws:lambda:us-west-2:123456789012:function:my-function\"}" -} -``` - -For more information about how to use Lambda with AWS IoT, see [Creating an AWS Lambda rule](https://docs.aws.amazon.com/iot/latest/developerguide/iot-lambda-rule.html)\. \ No newline at end of file diff --git a/doc_source/services-iotevents.md b/doc_source/services-iotevents.md deleted file mode 100644 index 2f43e48f..00000000 --- a/doc_source/services-iotevents.md +++ /dev/null @@ -1,60 +0,0 @@ -# Using AWS Lambda with AWS IoT Events - -AWS IoT Events monitors the inputs from multiple IoT sensors and applications to recognize event patterns\. Then it takes appropriate actions when events occur\. AWS IoT Events receives its inputs as JSON payloads from many sources\. AWS IoT Events supports simple events \(where each input triggers an event\) and complex events \(where multiple inputs must occur to trigger the event\)\. - -To use AWS IoT Events, you define a detector model, which is a state\-machine model of your equipment or process\. In addition to states, you define inputs and events for the model\. You also define the actions to take when an event occurs\. Use a Lambda function for an action when you want to invoke another AWS service \(such as Amazon Connect\), or take actions in an external application \(such as your enterprise resource planning \(ERP\) application\)\. - -When the event occurs, AWS IoT Events invokes your Lambda function asynchronously\. It provides information about the detector model and the event that triggered the action\. The following example message event is based on the definitions in the AWS IoT Events [simple step\-by\-step example](https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-simple-example.html)\. - -**Example Example AWS IoT Events message event** - -``` - -{ - "event: ":{ - "eventName": "myChargedEvent", - "eventTime": 1567797571647, - "payload":{ - "detector":{ - "detectorModelName": "AWS_IoTEvents_Hello_World1567793458261", - "detectorModelVersion": "4", - "keyValue": "100009" - }, - "eventTriggerDetails":{ - "triggerType": "Message", - "inputName": "AWS_IoTEvents_HelloWorld_VoltageInput", - "messageId": "64c75a34-068b-4a1d-ae58-c16215dc4efd" - }, - "actionExecutionId": "49f0f32f-1209-38a7-8a76-d6ca49dd0bc4", - "state":{ - "variables": {}, - "stateName": "Charged", - "timers": {} - } - } - } -} -``` - -The event that is passed into the Lambda function includes the following fields: -+ `eventName` – The name for this event in the detector model\. -+ `eventTime` – The time that the event occurred\. -+ `detector` – The name and version of the detector model\. -+ `eventTriggerDetails` – A description of the input that triggered the event\. -+ `actionExecutionId` – The unique execution identifier of the action\. -+ `state` – The state of the detector model when the event occurred\. - + `stateName` – The name of the state in the detector model\. - + `timers` – Any timers that are set in this state\. - + `variables` – Any variable values that are set in this state\. - -You need to grant permission for the AWS IoT Events service to invoke your Lambda function\. Use the `add-permission` command to add a permission statement to your function's resource\-based policy\. - -``` -$ aws lambda add-permission --function-name my-function \ ---statement-id iot-events --action "lambda:InvokeFunction" --principal iotevents.amazonaws.com -{ - "Statement": "{\"Sid\":\"iot-events\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"iotevents.amazonaws.com\"},\"Action\":\"lambda:InvokeFunction\",\"Resource\":\"arn:aws:lambda:us-west-2:123456789012:function:my-function\"}" -} -``` - -For more information about using Lambda with AWS IoT Events, see [Using AWS IoT Events with other services](https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-with-others.html)\. \ No newline at end of file diff --git a/doc_source/services-kinesisfirehose.md b/doc_source/services-kinesisfirehose.md deleted file mode 100644 index bc313be8..00000000 --- a/doc_source/services-kinesisfirehose.md +++ /dev/null @@ -1,41 +0,0 @@ -# Using AWS Lambda with Amazon Kinesis Data Firehose - -Amazon Kinesis Data Firehose captures, transforms, and loads streaming data into downstream services such as Kinesis Data Analytics or Amazon S3\. You can write Lambda functions to request additional, customized processing of the data before it is sent downstream\. - -**Example Amazon Kinesis Data Firehose message event** - -``` -{ - "invocationId": "invoked123", - "deliveryStreamArn": "aws:lambda:events", - "region": "us-west-2", - "records": [ - { - "data": "SGVsbG8gV29ybGQ=", - "recordId": "record1", - "approximateArrivalTimestamp": 1510772160000, - "kinesisRecordMetadata": { - "shardId": "shardId-000000000000", - "partitionKey": "4d1ad2b9-24f8-4b9d-a088-76e9947c317a", - "approximateArrivalTimestamp": "2012-04-23T18:25:43.511Z", - "sequenceNumber": "49546986683135544286507457936321625675700192471156785154", - "subsequenceNumber": "" - } - }, - { - "data": "SGVsbG8gV29ybGQ=", - "recordId": "record2", - "approximateArrivalTimestamp": 151077216000, - "kinesisRecordMetadata": { - "shardId": "shardId-000000000001", - "partitionKey": "4d1ad2b9-24f8-4b9d-a088-76e9947c318a", - "approximateArrivalTimestamp": "2012-04-23T19:25:43.511Z", - "sequenceNumber": "49546986683135544286507457936321625675700192471156785155", - "subsequenceNumber": "" - } - } - ] -} -``` - -For more information, see [Amazon Kinesis Data Firehose data transformation ](https://docs.aws.amazon.com/firehose/latest/dev/data-transformation.html) in the Kinesis Data Firehose Developer Guide\. \ No newline at end of file diff --git a/doc_source/services-lex.md b/doc_source/services-lex.md deleted file mode 100644 index 0049b611..00000000 --- a/doc_source/services-lex.md +++ /dev/null @@ -1,140 +0,0 @@ -# Using AWS Lambda with Amazon Lex - -You can use Amazon Lex to integrate a conversation bot into your application\. The Amazon Lex bot provides a conversational interface with your users\. Amazon Lex provides prebuilt integration with Lambda, which enables you to use a Lambda function with your Amazon Lex bot\. - -When you configure an Amazon Lex bot, you can specify a Lambda function to perform validation, fulfillment, or both\. For validation, Amazon Lex invokes the Lambda function after each response from the user\. The Lambda function can validate the response and provide corrective feedback to the user, if necessary\. For fulfillment, Amazon Lex invokes the Lambda function to fulfill the user request after the bot successfully collects all of the required information and receives confirmation from the user\. - -You can [manage the concurrency](configuration-concurrency.md) of your Lambda function to control the maximum number of simultaneous bot conversations that you serve\. The Amazon Lex API returns an HTTP 429 status code \(Too Many Requests\) if the function is at maximum concurrency\. - -The API returns an HTTP 424 status code \(Dependency Failed Exception\) if the Lambda function throws an exception\. - -The Amazon Lex bot invokes your Lambda function [synchronously](invocation-sync.md)\. The event parameter contains information about the bot and the value of each slot in the dialog\. The `invocationSource` parameter indicates whether the Lambda function should validate the inputs \(DialogCodeHook\) or fulfill the intent \(FulfillmentCodeHook\)\. - -**Example Amazon Lex message event** - -``` -{ - "messageVersion": "1.0", - "invocationSource": "FulfillmentCodeHook", - "userId": "ABCD1234", - "sessionAttributes": { - "key1": "value1", - "key2": "value2", - }, - "bot": { - "name": "OrderFlowers", - "alias": "prod", - "version": "1" - }, - "outputDialogMode": "Text", - "currentIntent": { - "name": "OrderFlowers", - "slots": { - "FlowerType": "lilies", - "PickupDate": "2030-11-08", - "PickupTime": "10:00" - }, - "confirmationStatus": "Confirmed" - } -} -``` - -Amazon Lex expects a response from a Lambda function in the following format\. The `dialogAction` field is required\. The `sessionAttributes` and the `recentIntentSummaryView` fields are optional\. - -**Example Amazon Lex message event** - -``` -{ - "sessionAttributes": { - "key1": "value1", - "key2": "value2" - ... - }, - "recentIntentSummaryView": [ - { - "intentName": "Name", - "checkpointLabel": "Label", - "slots": { - "slot name": "value", - "slot name": "value" - }, - "confirmationStatus": "None, Confirmed, or Denied (intent confirmation, if configured)", - "dialogActionType": "ElicitIntent, ElicitSlot, ConfirmIntent, Delegate, or Close", - "fulfillmentState": "Fulfilled or Failed", - "slotToElicit": "Next slot to elicit - } - ], - "dialogAction": { - "type": "Close", - "fulfillmentState": "Fulfilled", - "message": { - "contentType": "PlainText", - "content": "Thanks, your pizza has been ordered." - }, - "responseCard": { - "version": integer-value, - "contentType": "application/vnd.amazonaws.card.generic", - "genericAttachments": [ - { - "title":"card-title", - "subTitle":"card-sub-title", - "imageUrl":"URL of the image to be shown", - "attachmentLinkUrl":"URL of the attachment to be associated with the card", - "buttons":[ - { - "text":"button-text", - "value":"Value sent to server on button click" - } - ] - } - ] - } - } -} -``` - -Note that the additional fields required for `dialogAction` vary based on the value of the `type` field\. For more information about the event and response fields, see [Lambda event and response format](https://docs.aws.amazon.com/lex/latest/dg/lambda-input-response-format.html) in the *Amazon Lex Developer Guide*\. For an example tutorial that shows how to use Lambda with Amazon Lex, see [Exercise 1: Create Amazon Lex bot using a blueprint](https://docs.aws.amazon.com/lex/latest/dg/gs-bp.html) in the *Amazon Lex Developer Guide*\. - -## Roles and permissions - -You need to configure a service\-linked role as your function's [execution role](lambda-intro-execution-role.md)\. Amazon Lex defines the service\-linked role with predefined permissions\. When you create an Amazon Lex bot using the console, the service\-linked role is created automatically\. To create a service\-linked role with the AWS CLI, use the `create-service-linked-role` command\. - -``` -$ aws iam create-service-linked-role --aws-service-name lex.amazonaws.com -``` - -This command creates the following role\. - -``` -{ - "Role": { - "AssumeRolePolicyDocument": { - "Version": "2012-10-17", - "Statement": [ - { - "Action": "sts:AssumeRole", - "Effect": "Allow", - "Principal": { - "Service": "lex.amazonaws.com" - } - } - ] - }, - "RoleName": "AWSServiceRoleForLexBots", - "Path": "/aws-service-role/lex.amazonaws.com/", - "Arn": "arn:aws:iam::account-id:role/aws-service-role/lex.amazonaws.com/AWSServiceRoleForLexBots" -} -``` - - If your Lambda function uses other AWS services, you need to add the corresponding permissions to the service\-linked role\. - -You use a resource\-based permissions policy to allow the Amazon Lex intent to invoke your Lambda function\. If you use the Amazon Lex console, the permissions policy is created automatically\. From the AWS CLI, use the Lambda `add-permission` command to set the permission\. The following example sets permission for the `OrderFlowers` intent\. - -``` -aws lambda add-permission \ - --function-name OrderFlowersCodeHook \ - --statement-id LexGettingStarted-OrderFlowersBot \ - --action lambda:InvokeFunction \ - --principal lex.amazonaws.com \ - --source-arn "arn:aws:lex:us-east-1:123456789012 ID:intent:OrderFlowers:*" -``` \ No newline at end of file diff --git a/doc_source/services-rds-tutorial.md b/doc_source/services-rds-tutorial.md deleted file mode 100644 index 2424ff09..00000000 --- a/doc_source/services-rds-tutorial.md +++ /dev/null @@ -1,162 +0,0 @@ -# Tutorial: Configuring a Lambda function to access Amazon RDS in an Amazon VPC - -In this tutorial, you do the following: -+ Launch an Amazon RDS MySQL database engine instance in your default Amazon VPC\. In the MySQL instance, you create a database \(ExampleDB\) with a sample table \(Employee\) in it\. For more information about Amazon RDS, see [Amazon RDS](https://aws.amazon.com/rds)\. -+ Create a Lambda function to access the ExampleDB database, create a table \(Employee\), add a few records, and retrieve the records from the table\. -+ Invoke the Lambda function and verify the query results\. This is how you verify that your Lambda function was able to access the RDS MySQL instance in the VPC\. - -For details on using Lambda with Amazon VPC, see [Configuring a Lambda function to access resources in a VPC](configuration-vpc.md)\. - -## Prerequisites - -This tutorial assumes that you have some knowledge of basic Lambda operations and the Lambda console\. If you haven't already, follow the instructions in [Getting started with AWS Lambda](getting-started.md) to create your first Lambda function\. - -To follow the procedures in this guide, you will need a command line terminal or shell to run commands\. Commands are shown in listings preceded by a prompt symbol \($\) and the name of the current directory, when appropriate: - -``` -~/lambda-project$ this is a command -this is output -``` - -For long commands, an escape character \(`\`\) is used to split a command over multiple lines\. - -On Linux and macOS, use your preferred shell and package manager\. On Windows 10, you can [install the Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows\-integrated version of Ubuntu and Bash\. - -## Create the execution role - -Create the [execution role](lambda-intro-execution-role.md) that gives your function permission to access AWS resources\. - -**To create an execution role** - -1. Open the [roles page](https://console.aws.amazon.com/iam/home#/roles) in the IAM console\. - -1. Choose **Create role**\. - -1. Create a role with the following properties\. - + **Trusted entity** – Lambda\. - + **Permissions** – **AWSLambdaVPCAccessExecutionRole**\. - + **Role name** – **lambda\-vpc\-role**\. - -The **AWSLambdaVPCAccessExecutionRole** has the permissions that the function needs to manage network connections to a VPC\. - -## Create an Amazon RDS database instance - -In this tutorial, the example Lambda function creates a table \(Employee\), inserts a few records, and then retrieves the records\. The table that the Lambda function creates has the following schema: - -``` -Employee(EmpID, Name) -``` - -Where `EmpID` is the primary key\. Now, you need to add a few records to this table\. - -First, you launch an RDS MySQL instance in your default VPC with ExampleDB database\. If you already have an RDS MySQL instance running in your default VPC, skip this step\. - -You can launch an RDS MySQL instance using one of the following methods: -+ Follow the instructions at [Creating a MySQL DB instance and connecting to a database on a MySQL DB instance](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_GettingStarted.CreatingConnecting.MySQL.html) in the *Amazon RDS User Guide*\. -+ Use the following AWS CLI command: - - ``` - $ aws rds create-db-instance --db-name ExampleDB --engine MySQL \ - --db-instance-identifier MySQLForLambdaTest --backup-retention-period 3 \ - --db-instance-class db.t2.micro --allocated-storage 5 --no-publicly-accessible \ - --master-username username --master-user-password password - ``` - -Write down the database name, user name, and password\. You also need the host address \(endpoint\) of the DB instance, which you can get from the RDS console\. You might need to wait until the instance status is available and the Endpoint value appears in the console\. - -## Create a deployment package - -The following example Python code runs a SELECT query against the Employee table in the MySQL RDS instance that you created in the VPC\. The code creates a table in the ExampleDB database, adds sample records, and retrieves those records\. - -**Example app\.py** - -``` -import sys -import logging -import rds_config -import pymysql -#rds settings -rds_host = "rds-instance-endpoint" -name = rds_config.db_username -password = rds_config.db_password -db_name = rds_config.db_name - -logger = logging.getLogger() -logger.setLevel(logging.INFO) - -try: - conn = pymysql.connect(rds_host, user=name, passwd=password, db=db_name, connect_timeout=5) -except pymysql.MySQLError as e: - logger.error("ERROR: Unexpected error: Could not connect to MySQL instance.") - logger.error(e) - sys.exit() - -logger.info("SUCCESS: Connection to RDS MySQL instance succeeded") -def handler(event, context): - """ - This function fetches content from MySQL RDS instance - """ - - item_count = 0 - - with conn.cursor() as cur: - cur.execute("create table Employee ( EmpID int NOT NULL, Name varchar(255) NOT NULL, PRIMARY KEY (EmpID))") - cur.execute('insert into Employee (EmpID, Name) values(1, "Joe")') - cur.execute('insert into Employee (EmpID, Name) values(2, "Bob")') - cur.execute('insert into Employee (EmpID, Name) values(3, "Mary")') - conn.commit() - cur.execute("select * from Employee") - for row in cur: - item_count += 1 - logger.info(row) - #print(row) - conn.commit() - - return "Added %d items from RDS MySQL table" %(item_count) -``` - -Executing `pymysql.connect()` outside of the handler allows your function to re\-use the database connection for better performance\. - -A second file contains connection information for the function\. - -**Example rds\_config\.py** - -``` -#config file containing credentials for RDS MySQL instance -db_username = "username" -db_password = "password" -db_name = "ExampleDB" -``` - -**Dependencies** -+ `pymysql` – The Lambda function code uses this library to access your MySQL instance \(see [PyMySQL](https://pypi.python.org/pypi/PyMySQL)\) \. - -Install dependencies with Pip and create a deployment package\. For instructions, see [AWS Lambda deployment package in Python](python-package.md)\. - -## Create the Lambda function - -Create the Lambda function with the `create-function` command\. You can find the subnet IDs and security group ID for your default VPC in the [Amazon VPC console](https://console.aws.amazon.com/vpc)\. - -``` -$ aws lambda create-function --function-name CreateTableAddRecordsAndRead --runtime python3.8 \ ---zip-file fileb://app.zip --handler app.handler \ ---role arn:aws:iam::123456789012:role/lambda-vpc-role \ ---vpc-config SubnetIds=subnet-0532bb6758ce7c71f,subnet-d6b7fda068036e11f,SecurityGroupIds=sg-0897d5f549934c2fb -``` - -## Test the Lambda function - -In this step, you invoke the Lambda function manually using the `invoke` command\. When the Lambda function executes, it runs the SELECT query against the Employee table in the RDS MySQL instance and prints the results, which also go to the CloudWatch Logs\. - -1. Invoke the Lambda function with the `invoke` command\. - - ``` - $ aws lambda invoke --function-name CreateTableAddRecordsAndRead output.txt - ``` - -1. Verify that the Lambda function executed successfully as follows: - + Review the output\.txt file\. - + Review the results in the AWS Lambda console\. - + Verify the results in CloudWatch Logs\. - -Now that you have created a Lambda function that accesses a database in your VPC, you can have the function invoked in response to events\. For information about configuring event sources and examples, see [Using AWS Lambda with other services](lambda-services.md)\. \ No newline at end of file diff --git a/doc_source/services-rds.md b/doc_source/services-rds.md deleted file mode 100644 index ed77a1d4..00000000 --- a/doc_source/services-rds.md +++ /dev/null @@ -1,37 +0,0 @@ -# Using AWS Lambda with Amazon RDS - -You can use AWS Lambda to process event notifications from an Amazon Relational Database Service \(Amazon RDS\) database\. Amazon RDS sends notifications to an Amazon Simple Notification Service \(Amazon SNS\) topic, which you can configure to invoke a Lambda function\. Amazon SNS wraps the message from Amazon RDS in its own event document and sends it to your function\. - -**Example Amazon RDS message in an Amazon SNS event** - -``` -{ - "Records": [ - { - "EventVersion": "1.0", - "EventSubscriptionArn": "arn:aws:sns:us-east-2:123456789012:rds-lambda:21be56ed-a058-49f5-8c98-aedd2564c486", - "EventSource": "aws:sns", - "Sns": { - "SignatureVersion": "1", - "Timestamp": "2019-01-02T12:45:07.000Z", - "Signature": "tcc6faL2yUC6dgZdmrwh1Y4cGa/ebXEkAi6RibDsvpi+tE/1+82j...65r==", - "SigningCertUrl": "https://sns.us-east-2.amazonaws.com/SimpleNotificationService-ac565b8b1a6c5d002d285f9598aa1d9b.pem", - "MessageId": "95df01b4-ee98-5cb9-9903-4c221d41eb5e", - "Message": "{\"Event Source\":\"db-instance\",\"Event Time\":\"2019-01-02 12:45:06.000\",\"Identifier Link\":\"https://console.aws.amazon.com/rds/home?region=eu-west-1#dbinstance:id=dbinstanceid\",\"Source ID\":\"dbinstanceid\",\"Event ID\":\"http://docs.amazonwebservices.com/AmazonRDS/latest/UserGuide/USER_Events.html#RDS-EVENT-0002\",\"Event Message\":\"Finished DB Instance backup\"}", - "MessageAttributes": {}, - "Type": "Notification", - "UnsubscribeUrl": "https://sns.us-east-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-east-2:123456789012:test-lambda:21be56ed-a058-49f5-8c98-aedd2564c486", - "TopicArn":"arn:aws:sns:us-east-2:123456789012:sns-lambda", - "Subject": "RDS Notification Message" - } - } - ] -} -``` - -For instructions on configuring an Amazon RDS database to send notifications, see [Using Amazon RDS event notification](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_Events.html) in the Amazon Relational Database Service User Guide\. - -For details on using Amazon SNS as trigger, see [Using AWS Lambda with Amazon SNS](with-sns.md)\. - -**Topics** -+ [Tutorial: Configuring a Lambda function to access Amazon RDS in an Amazon VPC](services-rds-tutorial.md) \ No newline at end of file diff --git a/doc_source/services-s3-batch.md b/doc_source/services-s3-batch.md deleted file mode 100644 index 30e4d0bd..00000000 --- a/doc_source/services-s3-batch.md +++ /dev/null @@ -1,68 +0,0 @@ -# Using AWS Lambda with Amazon S3 batch operations - -You can use Amazon S3 batch operations to invoke a Lambda function on a large set of Amazon S3 objects\. Amazon S3 tracks the progress of batch operations, sends notifications, and stores a completion report that shows the status of each action\. - -To run a batch operation, you create an Amazon S3 [batch operations job](https://docs.aws.amazon.com/AmazonS3/latest/dev/batch-ops-operations.html)\. When you create the job, you provide a manifest \(the list of objects\) and configure the action to perform on those objects\. - -When the batch job starts, Amazon S3 invokes the Lambda function [synchronously](invocation-sync.md) for each object in the manifest\. The event parameter includes the names of the bucket and the object\. - -The following example shows the event that Amazon S3 sends to the Lambda function for an object that is named **customerImage1\.jpg** in the **awsexamplebucket** bucket\. - -**Example Example Amazon S3 batch request event** - -``` -{ -"invocationSchemaVersion": "1.0", - "invocationId": "YXNkbGZqYWRmaiBhc2RmdW9hZHNmZGpmaGFzbGtkaGZza2RmaAo", - "job": { - "id": "f3cc4f60-61f6-4a2b-8a21-d07600c373ce" - }, - "tasks": [ - { - "taskId": "dGFza2lkZ29lc2hlcmUK", - "s3Key": "customerImage1.jpg", - "s3VersionId": "1", - "s3BucketArn": "arn:aws:s3:us-east-1:0123456788:awsexamplebucket" - } - ] -} -``` - -Your Lambda function must return a JSON object with the fields as shown in the following example\. You can copy the `invocationId` and `taskId` from the event parameter\. You can return a string in the `resultString`\. Amazon S3 saves the `resultString` values in the completion report\. - -**Example Amazon S3 batch request response** - -``` -{ - "invocationSchemaVersion": "1.0", - "treatMissingKeysAs" : "PermanentFailure", - "invocationId" : "YXNkbGZqYWRmaiBhc2RmdW9hZHNmZGpmaGFzbGtkaGZza2RmaAo", - "results": [ - { - "taskId": "dGFza2lkZ29lc2hlcmUK", - "resultCode": "Succeeded", - "resultString": "["Alice", "Bob"]" - } - ] -} -``` - -## Invoking Lambda functions from Amazon S3 batch operations - -You can invoke the Lambda function with an unqualified or qualified function ARN\. If you want to use the same function version for the entire batch job, configure a specific function version in the `FunctionARN` parameter when you create your job\. If you configure an alias or the $LATEST qualifier, the batch job immediately starts calling the new version of the function if the alias or $LATEST is updated during the job execution\. - -Note that you can't reuse an existing Amazon S3 event\-based function for batch operations\. This is because the Amazon S3 batch operation passes a different event parameter to the Lambda function and expects a return message with a specific JSON structure\. - -In the [resource\-based policy](access-control-resource-based.md) that you create for the Amazon S3 batch job, ensure that you set permission for the job to invoke your Lambda function\. - -In the [execution role](lambda-intro-execution-role.md) for the function, set a trust policy for Amazon S3 to assume the role when it executes your function\. - -If your function uses the AWS SDK to manage Amazon S3 resources, you need to add Amazon S3 permissions in the execution role\. - -When the job executes, Amazon S3 starts multiple function instances to process the Amazon S3 objects in parallel, up to the [concurrency limit](invocation-scaling.md) of the function\. Amazon S3 limits the initial ramp\-up of instances to avoid excess cost for smaller jobs\. - -If the Lambda function returns a `TemporaryFailure` response code, Amazon S3 retries the operation\. - -For more information about Amazon S3 batch operations, see [Performing batch operations](https://docs.aws.amazon.com/AmazonS3/latest/dev/batch-ops.html) in the *Amazon S3 Developer Guide*\. - -For an example of how to use a Lambda function in Amazon S3 batch operations, see [Invoking a Lambda function from Amazon S3 batch operations](https://docs.aws.amazon.com/AmazonS3/latest/dev/batch-ops-invoke-lambda.html) in the *Amazon S3 Developer Guide*\. \ No newline at end of file diff --git a/doc_source/services-ses.md b/doc_source/services-ses.md deleted file mode 100644 index 43858e5c..00000000 --- a/doc_source/services-ses.md +++ /dev/null @@ -1,107 +0,0 @@ -# Using AWS Lambda with Amazon SES - -When you use Amazon SES to receive messages, you can configure Amazon SES to call your Lambda function when messages arrive\. The service can then invoke your Lambda function by passing in the incoming email event, which in reality is an Amazon SES message in an Amazon SNS event, as a parameter\. - -**Example Amazon SES message event** - -``` -{ - "Records": [ - { - "eventVersion": "1.0", - "ses": { - "mail": { - "commonHeaders": { - "from": [ - "Jane Doe " - ], - "to": [ - "johndoe@example.com" - ], - "returnPath": "janedoe@example.com", - "messageId": "<0123456789example.com>", - "date": "Wed, 7 Oct 2015 12:34:56 -0700", - "subject": "Test Subject" - }, - "source": "janedoe@example.com", - "timestamp": "1970-01-01T00:00:00.000Z", - "destination": [ - "johndoe@example.com" - ], - "headers": [ - { - "name": "Return-Path", - "value": "" - }, - { - "name": "Received", - "value": "from mailer.example.com (mailer.example.com [203.0.113.1]) by inbound-smtp.us-west-2.amazonaws.com with SMTP id o3vrnil0e2ic for johndoe@example.com; Wed, 07 Oct 2015 12:34:56 +0000 (UTC)" - }, - { - "name": "DKIM-Signature", - "value": "v=1; a=rsa-sha256; c=relaxed/relaxed; d=example.com; s=example; h=mime-version:from:date:message-id:subject:to:content-type; bh=jX3F0bCAI7sIbkHyy3mLYO28ieDQz2R0P8HwQkklFj4=; b=sQwJ+LMe9RjkesGu+vqU56asvMhrLRRYrWCbV" - }, - { - "name": "MIME-Version", - "value": "1.0" - }, - { - "name": "From", - "value": "Jane Doe " - }, - { - "name": "Date", - "value": "Wed, 7 Oct 2015 12:34:56 -0700" - }, - { - "name": "Message-ID", - "value": "<0123456789example.com>" - }, - { - "name": "Subject", - "value": "Test Subject" - }, - { - "name": "To", - "value": "johndoe@example.com" - }, - { - "name": "Content-Type", - "value": "text/plain; charset=UTF-8" - } - ], - "headersTruncated": false, - "messageId": "o3vrnil0e2ic28tr" - }, - "receipt": { - "recipients": [ - "johndoe@example.com" - ], - "timestamp": "1970-01-01T00:00:00.000Z", - "spamVerdict": { - "status": "PASS" - }, - "dkimVerdict": { - "status": "PASS" - }, - "processingTimeMillis": 574, - "action": { - "type": "Lambda", - "invocationType": "Event", - "functionArn": "arn:aws:lambda:us-west-2:012345678912:function:Example" - }, - "spfVerdict": { - "status": "PASS" - }, - "virusVerdict": { - "status": "PASS" - } - } - }, - "eventSource": "aws:ses" - } - ] -} -``` - -For more information, see [Lambda action](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-action-lambda.html) in the *Amazon SES Developer Guide*\. \ No newline at end of file diff --git a/doc_source/troubleshooting-deployment.md b/doc_source/troubleshooting-deployment.md deleted file mode 100644 index b73fa3c4..00000000 --- a/doc_source/troubleshooting-deployment.md +++ /dev/null @@ -1,92 +0,0 @@ -# Troubleshoot deployment issues in AWS Lambda - -When you update your function, Lambda deploys the change by launching new instances of the function with the updated code or settings\. Deployment errors prevent the new version from being used and can arise from issues with your deployment package, code, permissions, or tools\. - -When you deploy updates to your function directly with the Lambda API or with a client such as the AWS CLI, you can see errors from Lambda directly in the output\. If you use services like AWS CloudFormation, AWS CodeDeploy, or AWS CodePipeline, look for the response from Lambda in the logs or event stream for that service\. - -**Error:** *EACCES: permission denied, open '/var/task/index\.js'* - -**Error:** *cannot load such file \-\- function* - -**Error:** *\[Errno 13\] Permission denied: '/var/task/function\.py'* - -The Lambda runtime needs permission to read the files in your deployment package\. You can use the `chmod` command to change the file mode\. The following example commands make all files and folders in the current directory readable by any user\. - -``` -my-function$ chmod 644 $(find . -type f) -my-function$ chmod 755 $(find . -type d) -``` - -**Error:** *An error occurred \(RequestEntityTooLargeException\) when calling the UpdateFunctionCode operation* - -When you upload a deployment package or layer archive directly to Lambda, the size of the ZIP file is limited to 50 MB\. To upload a larger file, store it in Amazon S3 and use the [S3Bucket and S3Key](API_UpdateFunctionCode.md#SSS-UpdateFunctionCode-request-S3Bucket) parameters\. - -**Note** -When you upload a file directly with the AWS CLI, AWS SDK, or otherwise, the binary ZIP file is converted to base64, which increases its size by about 30%\. To allow for this, and the size of other parameters in the request, the actual request size limit that Lambda applies is larger\. Due to this, the 50 MB limit is approximate\. - -**Error:** *Error occurred while GetObject\. S3 Error Code: PermanentRedirect\. S3 Error Message: The bucket is in this region: us\-east\-2\. Please use this region to retry the request* - -When you upload a function's deployment package from an Amazon S3 bucket, the bucket must be in the same Region as the function\. This issue can occur when you specify an Amazon S3 object in a call to [UpdateFunctionCode](API_UpdateFunctionCode.md), or use the package and deploy commands in the AWS CLI or AWS SAM CLI\. Create a deployment artifact bucket for each Region where you develop applications\. - -**Error:** *Cannot find module 'function'* - -**Error:** *cannot load such file \-\- function* - -**Error:** *Unable to import module 'function'* - -**Error:** *Class not found: function\.Handler* - -**Error:** *fork/exec /var/task/function: no such file or directory* - -**Error:** *Unable to load type 'Function\.Handler' from assembly 'Function'\.* - -The name of the file or class in your function's handler configuration doesn't match your code\. See the following entry for more information\. - -**Error:** *index\.handler is undefined or not exported* - -**Error:** *Handler 'handler' missing on module 'function'* - -**Error:** *undefined method `handler' for \#* - -**Error:** *No public method named handleRequest with appropriate method signature found on class class function\.Handler* - -**Error:** *Unable to find method 'handleRequest' in type 'Function\.Handler' from assembly 'Function'* - -The name of the handler method in your function's handler configuration doesn't match your code\. Each runtime defines a naming convention for handlers, such as *filename*\.*methodname*\. The handler is the method in your function's code that the runtime executes when your function is invoked\. - -For some languages, Lambda provides a library with an interface that expects a handler method to have a specific name\. For details about handler naming for each language, see the following topics\. -+ [Building Lambda functions with Node\.js](lambda-nodejs.md) -+ [Building Lambda functions with Python](lambda-python.md) -+ [Building Lambda functions with Ruby](lambda-ruby.md) -+ [Building Lambda functions with Java](lambda-java.md) -+ [Building Lambda functions with Go](lambda-golang.md) -+ [Building Lambda functions with C\#](lambda-csharp.md) -+ [Building Lambda functions with PowerShell](lambda-powershell.md) - -**Error:** *InvalidParameterValueException: Lambda was unable to configure your environment variables because the environment variables you have provided exceeded the 4KB limit\. String measured: \{"A1":"uSFeY5cyPiPn7AtnX5BsM\.\.\.* - -**Error:** *RequestEntityTooLargeException: Request must be smaller than 5120 bytes for the UpdateFunctionConfiguration operation* - -The maximum size of the variables object that is stored in the function's configuration must not exceed 4096 bytes\. This includes key names, values, quotes, commas, and brackets\. The total size of the HTTP request body is also limited\. - -``` -{ - "FunctionName": "my-function", - "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function", - "Runtime": "nodejs12.x", - "Role": "arn:aws:iam::123456789012:role/lambda-role", - "Environment": { - "Variables": { - "BUCKET": "my-bucket", - "KEY": "file.txt" - } - }, - ... -} -``` - -In this example, the object is 39 characters and takes up 39 bytes when it's stored \(without white space\) as the string `{"BUCKET":"my-bucket","KEY":"file.txt"}`\. Standard ASCII characters in environment variable values use one byte each\. Extended ASCII and Unicode characters can use between 2 bytes and 4 bytes per character\. - -**Error:** *InvalidParameterValueException: Lambda was unable to configure your environment variables because the environment variables you have provided contains reserved keys that are currently not supported for modification\.* - -Lambda reserves some environment variable keys for internal use\. For example, `AWS_REGION` is used by the runtime to determine the current Region and cannot be overridden\. Other variables, like `PATH`, are used by the runtime but can be extended in your function configuration\. For a full list, see [Runtime environment variables](configuration-envvars.md#configuration-envvars-runtime)\. \ No newline at end of file diff --git a/doc_source/troubleshooting-execution.md b/doc_source/troubleshooting-execution.md deleted file mode 100644 index fcc117b1..00000000 --- a/doc_source/troubleshooting-execution.md +++ /dev/null @@ -1,46 +0,0 @@ -# Troubleshoot execution issues in AWS Lambda - -When the Lambda runtime executes your function code, the event might be processed on an instance of the function that's been processing events for some time, or it might require a new instance to be initialized\. Errors can occur when during function initialization, when your handler code processes the event, or when your function returns \(or fails to return\) a response\. - -Function execution errors can be caused by issues with your code, function configuration, downstream resources, or permissions\. If you invoke your function directly, you see function errors in the response from Lambda\. If you invoke your function asynchronously, with an event source mapping, or through another service, you might find errors in logs, a dead\-letter queue, or an on\-failure destination\. Error handling options and retry behavior vary depending on how you invoke your function and on the type of error\. - -When your function code or the Lambda runtime return an error, the status code in the response from Lambda is 200 OK\. The presence of an error in the response is indicated by a header named `X-Amz-Function-Error`\. 400 and 500\-series status codes are reserved for [invocation errors](troubleshooting-invocation.md)\. - -**Issue:** *Function execution takes too long\.* - -If your code takes much longer to run in Lambda than on your local machine, it may be constrained by the memory or processing power available to the function\. [Configure the function with additional memory](configuration-console.md) to increase both memory and CPU\. - -**Issue:** *Logs don't appear in CloudWatch Logs\.* - -**Issue:** *Traces don't appear in AWS X\-Ray\.* - -Your function needs permission to call CloudWatch Logs and X\-Ray\. Update its [execution role](lambda-intro-execution-role.md) to grant it permission\. Add the following managed policies to enable logs and tracing\. -+ **AWSLambdaBasicExecutionRole** -+ **AWSXRayDaemonWriteAccess** - -When you add permissions to your function, make an update to its code or configuration as well\. This forces running instances of your function, which have out\-of\-date credentials, to stop and be replaced\. - -**Issue: \(Node\.js\)** *Function returns before code finishes executing* - -Many libraries, including the AWS SDK, operate asynchronously\. When you make a network call or perform another operation that requires waiting for a response, libraries return an object called a promise that tracks the progress of the operation in the background\. - -To wait for the promise to resolve into a response, use the `await` keyword\. This blocks your handler code from executing until the promise is resolved into an object that contains the response\. If you don't need to use the data from the response in your code, you can return the promise directly to the runtime\. - -Some libraries don't return promises but can be wrapped in code that does\. For more information, see [AWS Lambda function handler in Node\.js](nodejs-handler.md)\. - -**Issue:** *The AWS SDK included on the runtime is not the latest version* - -**Issue:** *The AWS SDK included on the runtime updates automatically* - -Runtimes for scripting languages include the AWS SDK and are periodically updated to the latest version\. The current version for each runtime is listed on [runtimes page](lambda-runtimes.md)\. To use a newer version of the AWS SDK, or to lock your functions to a specific version, you can bundle the library with your function code, or [create a Lambda layer](configuration-layers.md)\. For details on creating a deployment package with dependencies, see the following topics: -+ [AWS Lambda deployment package in Node\.js](nodejs-package.md) -+ [AWS Lambda deployment package in Python](python-package.md) -+ [AWS Lambda deployment package in Ruby](ruby-package.md) -+ [AWS Lambda deployment package in Java](java-package.md) -+ [AWS Lambda deployment package in Go](golang-package.md) -+ [AWS Lambda Deployment Package in C\#](csharp-package.md) -+ [AWS Lambda deployment package in PowerShell](powershell-package.md) - -**Issue:** \(Python\) *Some libraries don't load correctly from the deployment package* - -Libraries with extension modules written in C or C\+\+ must be compiled in an environment with the same processor architecture as Lambda \(Amazon Linux\)\. For more information, see [AWS Lambda deployment package in Python](python-package.md)\. \ No newline at end of file diff --git a/doc_source/troubleshooting-invocation.md b/doc_source/troubleshooting-invocation.md deleted file mode 100644 index 5e4924b1..00000000 --- a/doc_source/troubleshooting-invocation.md +++ /dev/null @@ -1,47 +0,0 @@ -# Troubleshoot invocation issues in AWS Lambda - -When you invoke a Lambda function, Lambda validates the request and checks for scaling capacity before sending the event to your function or, for asynchronous invocation, to the event queue\. Invocation errors can be caused by issues with request parameters, event structure, function settings, user permissions, resource permissions, or limits\. - -If you invoke your function directly, you see invocation errors in the response from Lambda\. If you invoke your function asynchronously with an event source mapping or through another service, you might find errors in logs, a dead\-letter queue, or a failed\-event destination\. Error handling options and retry behavior vary depending on how you invoke your function and on the type of error\. - -For a list of error types that can be returned by the `Invoke` operation, see [Invoke](API_Invoke.md)\. - -**Error:** *User: arn:aws:iam::123456789012:user/developer is not authorized to perform: lambda:InvokeFunction on resource: my\-function* - -Your IAM user, or the role that you assume, needs permission to invoke a function\. This requirement also applies to Lambda functions and other compute resources that invoke functions\. Add the **AWSLambdaRole** managed policy, or a custom policy that allows the `lambda:InvokeFunction` action on the target function, to your IAM user\. - -**Note** -Unlike other API actions in Lambda, the name of the action in IAM \(`lambda:InvokeFunction`\) doesn't match the name of the API action \(`Invoke`\) for invoking a function\. - -For more information, see [AWS Lambda permissions](lambda-permissions.md)\. - -**Error:** *ResourceConflictException: The operation cannot be performed at this time\. The function is currently in the following state: Pending* - -When you connect a function to a VPC at the time of creation, the function enters a `Pending` state while Lambda creates elastic network interfaces\. During this time, you can't invoke or modify your function\. If you connect your function to a VPC after creation, you can invoke it while the update is pending, but you can't modify its code or configuration\. - -For more information, see [Monitoring the state of a function with the Lambda API](functions-states.md)\. - -**Error:** *A function is stuck in the `Pending` state for several minutes\.* - -If a function becomes stuck in the `Pending` state for more than six minutes, call one of the following API operations to unblock it\. -+ [UpdateFunctionCode](API_UpdateFunctionCode.md) -+ [UpdateFunctionConfiguration](API_UpdateFunctionConfiguration.md) -+ [PublishVersion](API_PublishVersion.md) - -Lambda cancels the pending operation and puts the function into the `Failed` state\. You can then delete the function and recreate it, or attempt another update\. - -**Issue:** *One function is using all of the available concurrency, causing other functions to be throttled\.* - -To divide the available concurrency in a Region into pools, use [reserved concurrency](configuration-concurrency.md)\. Reserved concurrency ensures that a function can always scale to its assigned concurrency, and also that it won't scale beyond its assigned concurrency\. - -**Issue:** *You can invoke your function directly, but it doesn't run when another service or account invokes it\.* - -You grant [other services](lambda-services.md) and accounts permission to invoke a function in the function's [resource\-based policy](access-control-resource-based.md)\. If the invoker is in another account, that user also needs [permission to invoke functions](access-control-identity-based.md)\. - -**Issue:** *Function is invoked continuously in a loop\.* - -This typically occurs when your function manages resources in the same AWS service that triggers it\. For example, it is possible to create a function that stores an object in an Amazon S3 bucket that is configured with a [notification that invokes the function again](with-s3.md)\. To stop the function from running, choose **Throttle** on the [function configuration page](configuration-console.md)\. Then identify the code path or configuration error that caused the recursive invocation\. - -**Error:** *KMSDisabledException: Lambda was unable to decrypt the environment variables because the KMS key used is disabled\. Please check the function's KMS key settings\.* - -This error can occur if your KMS key is disabled, or if the grant that allows Lambda to use the key is revoked\. If the grant is missing, configure the function to use a different key\. Then reassign the custom key to recreate the grant\. \ No newline at end of file diff --git a/doc_source/troubleshooting-networking.md b/doc_source/troubleshooting-networking.md deleted file mode 100644 index 743f0101..00000000 --- a/doc_source/troubleshooting-networking.md +++ /dev/null @@ -1,21 +0,0 @@ -# Troubleshoot networking issues in AWS Lambda - -By default, Lambda runs your functions in an internal virtual private cloud \(VPC\) with connectivity to AWS services and the internet\. To access local network resources, you can [configure your function to connect to a VPC in your account](configuration-vpc.md)\. When you use this feature, you manage the function's internet access and network connectivity with VPC resources\. - -Network connectivity errors can result from issues in routing configuration, security group rules, role permissions, network address translation, or the availability of resources such as IP addresses or network interfaces\. They may result in a specific error or, if a request can't reach its destination, a timeout\. - -**Issue:** *Function loses internet access after connecting to a VPC* - -**Error:** *Error: connect ETIMEDOUT 176\.32\.98\.189:443* - -**Error:** *Error: Task timed out after 10\.00 seconds* - -When you connect a function to a VPC, all outbound requests go through your VPC\. To connect to the internet, configure your VPC to send outbound traffic from the function's subnet to a NAT gateway in a public subnet\. For more information and sample VPC configurations, see [Internet and service access for VPC\-connected functions](configuration-vpc.md#vpc-internet)\. - -**Issue:** *Function needs access to AWS services without using the internet* - -To connect to AWS services from a private subnet with no internet access, use VPC endpoints\. For a sample template with VPC endpoints for DynamoDB and Amazon S3, see [Sample VPC configurations](configuration-vpc.md#vpc-samples)\. - -**Error:** *ENILimitReachedException: The elastic network interface limit was reached for the function's VPC\.* - -When you connect a function to a VPC, Lambda creates an elastic network interface for each combination of subnet and security group attached to the function\. These network interfaces are limited to 250 per VPC, but this limit can be increased\. To request an increase, use the [Support Center console](https://console.aws.amazon.com/support/v1#/case/create?issueType=service-limit-increase)\. \ No newline at end of file diff --git a/doc_source/using-x-ray.md b/doc_source/using-x-ray.md deleted file mode 100644 index 9d386621..00000000 --- a/doc_source/using-x-ray.md +++ /dev/null @@ -1,40 +0,0 @@ -# Tracing Lambda\-based applications with AWS X\-Ray - -AWS X\-Ray is an AWS service that allows you to detect, analyze, and optimize performance issues with your AWS Lambda applications\. X\-Ray collects metadata from the Lambda service and any upstream or downstream services that make up your application\. X\-Ray uses this metadata to generate a detailed service graph that illustrates performance bottlenecks, latency spikes, and other issues that impact the performance of your Lambda application\. - -After using the [Lambda on the AWS X\-Ray service map ](#lambda-service-map)to identify a problematic resource or component, you can zoom in and view a visual representation of the request\. This visual representation covers the time from when an event source triggers a Lambda function until the function execution has completed\. X\-Ray provides you with a breakdown of your function's operations, such as information regarding downstream calls your Lambda function made to other services\. In addition, X\-Ray integration with Lambda provides you with visibility into the AWS Lambda service overhead\. It does so by displaying specifics such as your request's dwell time and number of invocations\. - -**Note** -Only services that currently integrate with X\-Ray show as standalone traces, outside of your Lambda trace\. For a list of services that currently support X\-Ray, see [Integrating AWS X\-Ray with other AWS services](https://docs.aws.amazon.com/xray/latest/devguide/xray-services.html)\. - -## Lambda on the AWS X\-Ray service map - -X\-Ray displays three types of nodes on the service map for requests served by Lambda: -+ **Lambda service \(AWS::Lambda\)** – This type of node represents the time the request spent in the Lambda service\. Timing starts when Lambda first receives the request and ends when the request leaves the Lambda service\. -+ **Lambda function \(AWS::Lambda::Function\)** – This type of node represents the Lambda function's execution time\. -+ **Downstream service calls** – In this type, each downstream service call from within the Lambda function is represented by a separate node\. - -In the diagram following, the nodes represent \(from left to right\): The Lambda service, the user function, and a downstream call to Amazon S3: - -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/Tracing-S3.png) - -For more information, see [Viewing the service map](https://docs.aws.amazon.com/xray/latest/devguide/xray-console.html)\. - -## Lambda as an AWS X\-Ray trace - -From the service map, you can zoom in to see a trace view of your Lambda function\. The trace will display in\-depth information regarding your function invocations, represented as segments and subsegments: -+ **Lambda service segment** – This segment represents different information depending on the event source used to invoke the function: - + **Synchronous and stream event sources** – The service segment measures the time from when the Lambda service receives the request/event and ends when the request leaves the Lambda service \(after the final invocation for the request is completed\)\. - + **Asynchronous** – The service segment represents the response time, that is, the time it took the Lambda service to return a 202 response to the client\. - - The Lambda service segment can include two types of subsegments: - + **Dwell time \(asynchronous invocations only\)** – Represents the time the function spends in the Lambda service before being invoked\. This subsegment starts when the Lambda service receives the request/event and ends when the Lambda function is invoked for the first time\. - + **Attempt** – Represents a single invocation attempt, including any overhead introduced by the Lambda service\. Examples of overhead are time spent initializing the function's code and function execution time\. -+ **Lambda function segment** – Represents execution time for the function for a given invocation attempt\. It starts when the function handler starts executing and ends when the function terminates\. This segment can include three types of subsegments: - + **Initialization** – The time spent running the `initialization` code of the function, defined as the code outside the Lambda function handler or static initializers\. - + **Downstream calls** – Calls made to other AWS services or downstream HTTP requests from the Lambda function's code\. - + **Custom subsegments** – Custom subsegments that you can add to the Lambda function segment by using the X\-Ray SDK\. - -The Lambda function segment is generated by the Lambda service on behalf of the customer\. It overwrites any segment created in the Lambda function code, including segments generated by the X\-Ray SDK to capture requests via middleware\. If a segment is created in Lambda function code, it is implemented as a facade segment\. The facade segment only allows custom subsegments to be added to and deleted from it; all other segment operations are treated as no\-ops\. - -For each traced invocation, Lambda emits the Lambda service segment and all of its subsegments\. This segment and its subsegments are emitted regardless of the runtime you use\. \ No newline at end of file diff --git a/doc_source/welcome.md b/doc_source/welcome.md deleted file mode 100644 index c6c2ce8a..00000000 --- a/doc_source/welcome.md +++ /dev/null @@ -1,31 +0,0 @@ -# What is AWS Lambda? - - AWS Lambda is a compute service that lets you run code without provisioning or managing servers\. AWS Lambda executes your code only when needed and scales automatically, from a few requests per day to thousands per second\. You pay only for the compute time you consume \- there is no charge when your code is not running\. With AWS Lambda, you can run code for virtually any type of application or backend service \- all with zero administration\. AWS Lambda runs your code on a high\-availability compute infrastructure and performs all of the administration of the compute resources, including server and operating system maintenance, capacity provisioning and automatic scaling, code monitoring and logging\. All you need to do is supply your code in one of the [languages that AWS Lambda supports](lambda-runtimes.md)\. - -You can use AWS Lambda to run your code in response to events, such as changes to data in an Amazon S3 bucket or an Amazon DynamoDB table; to run your code in response to HTTP requests using Amazon API Gateway; or invoke your code using API calls made using AWS SDKs\. With these capabilities, you can use Lambda to easily build data processing triggers for AWS services like Amazon S3 and Amazon DynamoDB, process streaming data stored in Kinesis, or create your own back end that operates at AWS scale, performance, and security\. - -You can also build serverless applications composed of functions that are triggered by events and automatically deploy them using CodePipeline and AWS CodeBuild\. For more information, see [AWS Lambda applications](deploying-lambda-apps.md)\. - -## When should I use AWS Lambda? - -AWS Lambda is an ideal compute platform for many application scenarios, provided that you can write your application code in languages supported by AWS Lambda, and run within the AWS Lambda standard runtime environment and resources provided by Lambda\. - -When using AWS Lambda, you are responsible only for your code\. AWS Lambda manages the compute fleet that offers a balance of memory, CPU, network, and other resources\. This is in exchange for flexibility, which means you cannot log in to compute instances, or customize the operating system on provided runtimes\. These constraints enable AWS Lambda to perform operational and administrative activities on your behalf, including provisioning capacity, monitoring fleet health, applying security patches, deploying your code, and monitoring and logging your Lambda functions\. - -If you need to manage your own compute resources, Amazon Web Services also offers other compute services to meet your needs\. -+ Amazon Elastic Compute Cloud \(Amazon EC2\) service offers flexibility and a wide range of EC2 instance types to choose from\. It gives you the option to customize operating systems, network and security settings, and the entire software stack, but you are responsible for provisioning capacity, monitoring fleet health and performance, and using Availability Zones for fault tolerance\. -+ Elastic Beanstalk offers an easy\-to\-use service for deploying and scaling applications onto Amazon EC2 in which you retain ownership and full control over the underlying EC2 instances\. - -Lambda is a highly available service\. For more information, see the [AWS Lambda service level agreement](https://aws.amazon.com/lambda/sla/)\. - -## Are you a first\-time user of AWS Lambda? - -If you are a first\-time user of AWS Lambda, we recommend that you read the following sections in order: - -1. **Read the product overview and watch the introductory video to understand sample use cases\.** These resources are available on the [AWS Lambda webpage](https://aws.amazon.com/lambda/)\. - -1. **Try the console\-based getting started exercise\.** The exercise provides instructions for you to create and test your first Lambda function using the console\. You also learn about the programming model and other Lambda concepts\. For more information, see [Getting started with AWS Lambda](getting-started.md)\. - -1. **Read the [deploying applications with AWS Lambda](deploying-lambda-apps.md) section of this guide\. **This section introduces various AWS Lambda components you work with to create an end\-to\-end experience\. - -Beyond the Getting Started exercise, you can explore the various use cases, each of which is provided with a tutorial that walks you through an example scenario\. Depending on your application needs \(for example, whether you want event driven Lambda function invocation or on\-demand invocation\), you can follow specific tutorials that meet your specific needs\. For more information, see [Using AWS Lambda with other services](lambda-services.md)\. \ No newline at end of file diff --git a/doc_source/with-android-create-package.md b/doc_source/with-android-create-package.md deleted file mode 100644 index e7348f2d..00000000 --- a/doc_source/with-android-create-package.md +++ /dev/null @@ -1,103 +0,0 @@ -# Sample function code - -Sample code is available for the following languages\. - -**Topics** -+ [Node\.js](#with-android-example-deployment-pkg-nodejs) -+ [Java](#with-on-demand-custom-android-example-deployment-pkg-java) - -## Node\.js - -The following example uses data to generate a string response\. - -**Example index\.js** - -``` -exports.handler = function(event, context, callback) { - console.log("Received event: ", event); - var data = { - "greetings": "Hello, " + event.firstName + " " + event.lastName + "." - }; - callback(null, data); -} -``` - -Zip up the sample code to create a deployment package\. For instructions, see [AWS Lambda deployment package in Node\.js](nodejs-package.md)\. - -## Java - -The following example uses data to generate a string response\. - -In the code, the `handler` \(`myHandler`\) uses the `RequestClass` and `ResponseClass` types for the input and output\. The code provides implementation for these types\. - -**Example HelloPojo\.java** - -``` -package example; - -import com.amazonaws.services.lambda.runtime.Context; - -public class HelloPojo { - - // Define two classes/POJOs for use with Lambda function. - public static class RequestClass { - String firstName; - String lastName; - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public RequestClass(String firstName, String lastName) { - this.firstName = firstName; - this.lastName = lastName; - } - - public RequestClass() { - } - } - - public static class ResponseClass { - String greetings; - - public String getGreetings() { - return greetings; - } - - public void setGreetings(String greetings) { - this.greetings = greetings; - } - - public ResponseClass(String greetings) { - this.greetings = greetings; - } - - public ResponseClass() { - } - - } - - public static ResponseClass myHandler(RequestClass request, Context context){ - String greetingString = String.format("Hello %s, %s.", request.firstName, request.lastName); - context.getLogger().log(greetingString); - return new ResponseClass(greetingString); - } -} -``` - -**Dependencies** -+ `aws-lambda-java-core` - -Build the code with the Lambda library dependencies to create a deployment package\. For instructions, see [AWS Lambda deployment package in Java](java-package.md)\. \ No newline at end of file diff --git a/doc_source/with-android-example.md b/doc_source/with-android-example.md deleted file mode 100644 index 360ccbad..00000000 --- a/doc_source/with-android-example.md +++ /dev/null @@ -1,313 +0,0 @@ -# Tutorial: Using AWS Lambda with the Mobile SDK for Android - -In this tutorial, you create a simple Android mobile application that uses Amazon Cognito to get credentials and invokes a Lambda function\. - -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/lambda-android.png) - -The mobile application retrieves AWS credentials from an Amazon Cognito identity pool and uses them to invoke a Lambda function with an event that contains request data\. The function processes the request and returns a response to the front\-end\. - -## Prerequisites - -This tutorial assumes that you have some knowledge of basic Lambda operations and the Lambda console\. If you haven't already, follow the instructions in [Getting started with AWS Lambda](getting-started.md) to create your first Lambda function\. - -To follow the procedures in this guide, you will need a command line terminal or shell to run commands\. Commands are shown in listings preceded by a prompt symbol \($\) and the name of the current directory, when appropriate: - -``` -~/lambda-project$ this is a command -this is output -``` - -For long commands, an escape character \(`\`\) is used to split a command over multiple lines\. - -On Linux and macOS, use your preferred shell and package manager\. On Windows 10, you can [install the Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows\-integrated version of Ubuntu and Bash\. - -## Create the execution role - -Create the [execution role](lambda-intro-execution-role.md) that gives your function permission to access AWS resources\. - -**To create an execution role** - -1. Open the [roles page](https://console.aws.amazon.com/iam/home#/roles) in the IAM console\. - -1. Choose **Create role**\. - -1. Create a role with the following properties\. - + **Trusted entity** – **AWS Lambda**\. - + **Permissions** – **AWSLambdaBasicExecutionRole**\. - + **Role name** – **lambda\-android\-role**\. - -The **AWSLambdaBasicExecutionRole** policy has the permissions that the function needs to write logs to CloudWatch Logs\. - -## Create the function - -The following example uses data to generate a string response\. - -**Note** -For sample code in other languages, see [Sample function code](with-android-create-package.md)\. - -**Example index\.js** - -``` -exports.handler = function(event, context, callback) { - console.log("Received event: ", event); - var data = { - "greetings": "Hello, " + event.firstName + " " + event.lastName + "." - }; - callback(null, data); -} -``` - -**To create the function** - -1. Copy the sample code into a file named `index.js`\. - -1. Create a deployment package\. - - ``` - $ zip function.zip index.js - ``` - -1. Create a Lambda function with the `create-function` command\. - - ``` - $ aws lambda create-function --function-name AndroidBackendLambdaFunction \ - --zip-file fileb://function.zip --handler index.handler --runtime nodejs12.x \ - --role arn:aws:iam::123456789012:role/lambda-android-role - ``` - -## Test the Lambda function - -Invoke the function manually using the sample event data\. - -**To test the Lambda function \(AWS CLI\)** - -1. Save the following sample event JSON in a file, `input.txt`\. - - ``` - { "firstName": "first-name", "lastName": "last-name" } - ``` - -1. Execute the following `invoke` command: - - ``` - $ aws lambda invoke --function-name AndroidBackendLambdaFunction \ - --payload file://file-path/input.txt outputfile.txt - ``` - -## Create an Amazon Cognito identity pool - -In this section, you create an Amazon Cognito identity pool\. The identity pool has two IAM roles\. You update the IAM role for unauthenticated users and grant permissions to execute the `AndroidBackendLambdaFunction` Lambda function\. - -For more information about IAM roles, see [IAM roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) in the *IAM User Guide*\. For more information about Amazon Cognito services, see the [Amazon Cognito](https://aws.amazon.com/cognito/) product detail page\. - -**To create an identity pool** - -1. Open the [Amazon Cognito console](https://console.aws.amazon.com/cognito)\. - -1. Create a new identity pool called `JavaFunctionAndroidEventHandlerPool`\. Before you follow the procedure to create an identity pool, note the following: - + The identity pool you are creating must allow access to unauthenticated identities because our example mobile application does not require a user log in\. Therefore, make sure to select the **Enable access to unauthenticated identities** option\. - + Add the following statement to the permission policy associated with the unauthenticated identities\. - - ``` - { - "Effect": "Allow", - "Action": [ - "lambda:InvokeFunction" - ], - "Resource": [ - "arn:aws:lambda:us-east-1:123456789012:function:AndroidBackendLambdaFunction" - ] - } - ``` - - The resulting policy will be as follows: - - ``` - { - "Version":"2012-10-17", - "Statement":[ - { - "Effect":"Allow", - "Action":[ - "mobileanalytics:PutEvents", - "cognito-sync:*" - ], - "Resource":[ - "*" - ] - }, - { - "Effect":"Allow", - "Action":[ - "lambda:invokefunction" - ], - "Resource":[ - "arn:aws:lambda:us-east-1:account-id:function:AndroidBackendLambdaFunction" - ] - } - ] - } - ``` - - For instructions about how to create an identity pool, log in to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home) and follow the **New Identity Pool** wizard\. - -1. Note the identity pool ID\. You specify this ID in your mobile application you create in the next section\. The app uses this ID when it sends request to Amazon Cognito to request for temporary security credentials\. - -## Create an Android application - -Create a simple Android mobile application that generates events and invokes Lambda functions by passing the event data as parameters\. - -The following instructions have been verified using Android studio\. - -1. Create a new Android project called `AndroidEventGenerator` using the following configuration: - + Select the **Phone and Tablet** platform\. - + Choose **Blank Activity**\. - -1. In the build\.gradle \(`Module:app`\) file, add the following in the `dependencies` section: - - ``` - compile 'com.amazonaws:aws-android-sdk-core:2.2.+' - compile 'com.amazonaws:aws-android-sdk-lambda:2.2.+' - ``` - -1. Build the project so that the required dependencies are downloaded, as needed\. - -1. In the Android application manifest \(`AndroidManifest.xml`\), add the following permissions so that your application can connect to the Internet\. You can add them just before the `` end tag\. - - ``` - - - ``` - -1. In `MainActivity`, add the following imports: - - ``` - import com.amazonaws.mobileconnectors.lambdainvoker.*; - import com.amazonaws.auth.CognitoCachingCredentialsProvider; - import com.amazonaws.regions.Regions; - ``` - -1. In the `package` section, add the following two classes \(`RequestClass` and `ResponseClass`\)\. Note that the POJO is same as the POJO you created in your Lambda function in the preceding section\. - + `RequestClass`\. The instances of this class act as the POJO \(Plain Old Java Object\) for event data which consists of first and last name\. If you are using Java example for your Lambda function you created in the preceding section, this POJO is same as the POJO you created in your Lambda function code\. - - ``` - package com.example....lambdaeventgenerator; - public class RequestClass { - String firstName; - String lastName; - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public RequestClass(String firstName, String lastName) { - this.firstName = firstName; - this.lastName = lastName; - } - - public RequestClass() { - } - } - ``` - + `ResponseClass` - - ``` - package com.example....lambdaeventgenerator; - public class ResponseClass { - String greetings; - - public String getGreetings() { - return greetings; - } - - public void setGreetings(String greetings) { - this.greetings = greetings; - } - - public ResponseClass(String greetings) { - this.greetings = greetings; - } - - public ResponseClass() { - } - } - ``` - -1. In the same package, create interface called `MyInterface` for invoking the `AndroidBackendLambdaFunction` Lambda function\. - - ``` - package com.example.....lambdaeventgenerator; - import com.amazonaws.mobileconnectors.lambdainvoker.LambdaFunction; - public interface MyInterface { - - /** - * Invoke the Lambda function "AndroidBackendLambdaFunction". - * The function name is the method name. - */ - @LambdaFunction - ResponseClass AndroidBackendLambdaFunction(RequestClass request); - - } - ``` - - The `@LambdaFunction` annotation in the code maps the specific client method to the same\-name Lambda function\. - -1. To keep the application simple, we are going to add code to invoke the Lambda function in the `onCreate()` event handler\. In `MainActivity`, add the following code toward the end of the `onCreate()` code\. - - ``` - // Create an instance of CognitoCachingCredentialsProvider - CognitoCachingCredentialsProvider cognitoProvider = new CognitoCachingCredentialsProvider( - this.getApplicationContext(), "identity-pool-id", Regions.US_WEST_2); - - // Create LambdaInvokerFactory, to be used to instantiate the Lambda proxy. - LambdaInvokerFactory factory = new LambdaInvokerFactory(this.getApplicationContext(), - Regions.US_WEST_2, cognitoProvider); - - // Create the Lambda proxy object with a default Json data binder. - // You can provide your own data binder by implementing - // LambdaDataBinder. - final MyInterface myInterface = factory.build(MyInterface.class); - - RequestClass request = new RequestClass("John", "Doe"); - // The Lambda function invocation results in a network call. - // Make sure it is not called from the main thread. - new AsyncTask() { - @Override - protected ResponseClass doInBackground(RequestClass... params) { - // invoke "echo" method. In case it fails, it will throw a - // LambdaFunctionException. - try { - return myInterface.AndroidBackendLambdaFunction(params[0]); - } catch (LambdaFunctionException lfe) { - Log.e("Tag", "Failed to invoke echo", lfe); - return null; - } - } - - @Override - protected void onPostExecute(ResponseClass result) { - if (result == null) { - return; - } - - // Do a toast - Toast.makeText(MainActivity.this, result.getGreetings(), Toast.LENGTH_LONG).show(); - } - }.execute(request); - ``` - -1. Run the code and verify it as follows: - + The `Toast.makeText()` displays the response returned\. - + Verify that CloudWatch Logs shows the log created by the Lambda function\. It should show the event data \(first name and last name\)\. You can also verify this in the AWS Lambda console\. \ No newline at end of file diff --git a/doc_source/with-cloudtrail-create-package.md b/doc_source/with-cloudtrail-create-package.md deleted file mode 100644 index 9e2b54b5..00000000 --- a/doc_source/with-cloudtrail-create-package.md +++ /dev/null @@ -1,91 +0,0 @@ -# Sample function code - -Sample code is available for the following languages\. - -**Topics** -+ [Node\.js](#with-cloudtrail-example-deployment-pkg-nodejs) - -## Node\.js - -The following example processes CloudTrail logs, and sends a notification when an Amazon SNS topic was created\. - -**Example index\.js** - -``` -var aws = require('aws-sdk'); -var zlib = require('zlib'); -var async = require('async'); - -var EVENT_SOURCE_TO_TRACK = /sns.amazonaws.com/; -var EVENT_NAME_TO_TRACK = /CreateTopic/; -var DEFAULT_SNS_REGION = 'us-west-2'; -var SNS_TOPIC_ARN = 'The ARN of your SNS topic'; - -var s3 = new aws.S3(); -var sns = new aws.SNS({ - apiVersion: '2010-03-31', - region: DEFAULT_SNS_REGION -}); - -exports.handler = function(event, context, callback) { - var srcBucket = event.Records[0].s3.bucket.name; - var srcKey = event.Records[0].s3.object.key; - - async.waterfall([ - function fetchLogFromS3(next){ - console.log('Fetching compressed log from S3...'); - s3.getObject({ - Bucket: srcBucket, - Key: srcKey - }, - next); - }, - function uncompressLog(response, next){ - console.log("Uncompressing log..."); - zlib.gunzip(response.Body, next); - }, - function publishNotifications(jsonBuffer, next) { - console.log('Filtering log...'); - var json = jsonBuffer.toString(); - console.log('CloudTrail JSON from S3:', json); - var records; - try { - records = JSON.parse(json); - } catch (err) { - next('Unable to parse CloudTrail JSON: ' + err); - return; - } - var matchingRecords = records - .Records - .filter(function(record) { - return record.eventSource.match(EVENT_SOURCE_TO_TRACK) - && record.eventName.match(EVENT_NAME_TO_TRACK); - }); - - console.log('Publishing ' + matchingRecords.length + ' notification(s) in parallel...'); - async.each( - matchingRecords, - function(record, publishComplete) { - console.log('Publishing notification: ', record); - sns.publish({ - Message: - 'Alert... SNS topic created: \n TopicARN=' + record.responseElements.topicArn + '\n\n' + - JSON.stringify(record), - TopicArn: SNS_TOPIC_ARN - }, publishComplete); - }, - next - ); - } - ], function (err) { - if (err) { - console.error('Failed to publish notifications: ', err); - } else { - console.log('Successfully published all notifications.'); - } - callback(null,"message"); - }); -}; -``` - -Zip up the sample code to create a deployment package\. For instructions, see [AWS Lambda deployment package in Node\.js](nodejs-package.md)\. \ No newline at end of file diff --git a/doc_source/with-cloudtrail-example.md b/doc_source/with-cloudtrail-example.md deleted file mode 100644 index b6f6a2d0..00000000 --- a/doc_source/with-cloudtrail-example.md +++ /dev/null @@ -1,254 +0,0 @@ -# Tutorial: Triggering a Lambda function with AWS CloudTrail events - -You can configure Amazon S3 to publish events to AWS Lambda when AWS CloudTrail stores API call logs\. Your Lambda function can read the log object and process the access records logged by CloudTrail\. - -Use the following instructions to create a Lambda function that notifies you when a specific API call is made in your account\. The function processes notification events from Amazon S3, reads logs from a bucket, and publishes alerts through an Amazon SNS topic\. For this tutorial, you create: -+ A CloudTrail trail and an S3 bucket to save logs to\. -+ An Amazon SNS topic to publish alert notifications\. -+ An IAM user role with permissions to read items from an S3 bucket and write logs to Amazon CloudWatch\. -+ A Lambda function that processes CloudTrail logs and sends a notification whenever an Amazon SNS topic is created\. - -## Requirements - -This tutorial assumes that you have some knowledge of basic Lambda operations and the Lambda console\. If you haven't already, follow the instructions in [Getting started with AWS Lambda](getting-started.md) to create your first Lambda function\. - -Before you begin, make sure that you have the following tools: -+ [Node\.js 8 with `npm`](https://nodejs.org/en/download/releases/)\. -+ The Bash shell\. For Linux and macOS, this is included by default\. In Windows 10, you can install the [Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows\-integrated version of Ubuntu and Bash\. -+ [The AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html)\. - -## Step 1: Creating a trail in CloudTrail - -When you create a trail, CloudTrail records the API calls in log files and stores them in Amazon S3\. A CloudTrail log is an unordered array of events in JSON format\. For each call to a supported API action, CloudTrail records information about the request and the entity that made it\. Log events include the action name, parameters, response values, and details about the requester\. - -**To create a trail** - -1. Open the [**Trails** page of the CloudTrail console](https://console.aws.amazon.com/cloudtrail/home#/configuration)\. - -1. Choose **Create trail**\. - -1. For **Trail name**, enter a name\. - -1. For **S3 bucket**, enter a name\. - -1. Choose **Create**\. - -1. Save the bucket Amazon Resource Name \(ARN\) to add it to the IAM execution role, which you create later\. - -## Step 2: Creating an Amazon SNS topic - - Create an Amazon SNS topic to send out a notification when new object events have occurred\. - -**To create a topic** - -1. Open the [**Topics** page of the Amazon SNS console](https://console.aws.amazon.com/sns/home#/topics)\. - -1. Choose **Create topic**\. - -1. For **Topic name**, enter a name\. - -1. Choose **Create topic**\. - -1. Record the topic ARN\. You will need it when you create the IAM execution role and Lambda function\. - -## Step 3: Creating an IAM execution role - -An [execution role](lambda-intro-execution-role.md) gives your function permission to access AWS resources\. Create an execution role that grants the function permission to access CloudWatch Logs, Amazon S3, and Amazon SNS\. - -**To create an execution role** - -1. Open the [**Roles** page](https://console.aws.amazon.com/iam/home#/roles) of the IAM console\. - -1. Choose **Create role**\. - -1. Create a role with the following properties: - + For **Trusted entity**, choose **Lambda**\. - + For **Role name**, enter **lambda\-cloudtrail\-role**\. - + For **Permissions**, create a custom policy with the following statements\. Replace the highlighted values with the names of your bucket and topic\. - - ``` - { - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Allow", - "Action": [ - "logs:*" - ], - "Resource": "arn:aws:logs:*:*:*" - }, - { - "Effect": "Allow", - "Action": [ - "s3:GetObject" - ], - "Resource": "arn:aws:s3:::my-bucket/*" - }, - { - "Effect": "Allow", - "Action": [ - "sns:Publish" - ], - "Resource": "arn:aws:sns:us-west-2:123456789012:my-topic" - } - ] - } - ``` - -1. Record the role ARN\. You will need it when you create the Lambda function\. - -## Step 4: Creating the Lambda function - -The following Lambda function processes CloudTrail logs, and sends a notification through Amazon SNS when a new Amazon SNS topic is created\. - -**To create the function** - -1. Create a folder and give it a name that indicates that it's your Lambda function \(for example, *lambda\-cloudtrail*\)\. - -1. In the folder, create a file named `index.js`\. - -1. Paste the following code into `index.js`\. Replace the Amazon SNS topic ARN with the ARN that Amazon S3 created when you created the Amazon SNS topic\. - - ``` - var aws = require('aws-sdk'); - var zlib = require('zlib'); - var async = require('async'); - - var EVENT_SOURCE_TO_TRACK = /sns.amazonaws.com/; - var EVENT_NAME_TO_TRACK = /CreateTopic/; - var DEFAULT_SNS_REGION = 'us-east-2'; - var SNS_TOPIC_ARN = 'arn:aws:sns:us-west-2:123456789012:my-topic'; - - var s3 = new aws.S3(); - var sns = new aws.SNS({ - apiVersion: '2010-03-31', - region: DEFAULT_SNS_REGION - }); - - exports.handler = function(event, context, callback) { - var srcBucket = event.Records[0].s3.bucket.name; - var srcKey = event.Records[0].s3.object.key; - - async.waterfall([ - function fetchLogFromS3(next){ - console.log('Fetching compressed log from S3...'); - s3.getObject({ - Bucket: srcBucket, - Key: srcKey - }, - next); - }, - function uncompressLog(response, next){ - console.log("Uncompressing log..."); - zlib.gunzip(response.Body, next); - }, - function publishNotifications(jsonBuffer, next) { - console.log('Filtering log...'); - var json = jsonBuffer.toString(); - console.log('CloudTrail JSON from S3:', json); - var records; - try { - records = JSON.parse(json); - } catch (err) { - next('Unable to parse CloudTrail JSON: ' + err); - return; - } - var matchingRecords = records - .Records - .filter(function(record) { - return record.eventSource.match(EVENT_SOURCE_TO_TRACK) - && record.eventName.match(EVENT_NAME_TO_TRACK); - }); - - console.log('Publishing ' + matchingRecords.length + ' notification(s) in parallel...'); - async.each( - matchingRecords, - function(record, publishComplete) { - console.log('Publishing notification: ', record); - sns.publish({ - Message: - 'Alert... SNS topic created: \n TopicARN=' + record.responseElements.topicArn + '\n\n' + - JSON.stringify(record), - TopicArn: SNS_TOPIC_ARN - }, publishComplete); - }, - next - ); - } - ], function (err) { - if (err) { - console.error('Failed to publish notifications: ', err); - } else { - console.log('Successfully published all notifications.'); - } - callback(null,"message"); - }); - }; - ``` - -1. In the *lambda\-cloudtrail* folder, run the following script\. It creates a `package-lock.json` file and a `node_modules` folder, which handle all dependencies\. - - ``` - $ npm install async - ``` - -1. Run the following script to create a deployment package\. - - ``` - $ zip -r function.zip . - ``` - -1. Create a Lambda function named CloudTrailEventProcessing with the `create-function` command by running the following script\. Make the indicated replacements\. - - ``` - $ aws lambda create-function --function-name CloudTrailEventProcessing \ - --zip-file fileb://function.zip --handler index.handler --runtime nodejs12.x --timeout 10 --memory-size 1024 \ - --role arn:aws:iam::123456789012:role/lambda-cloudtrail-role - ``` - -## Step 5: Adding permissions to the Lambda function policy - -The Lambda function's resource policy needs permissions to allow Amazon S3 to invoke the function\. - -**To give Amazon S3 permissions to invoke the function** - -1. Run the following `add-permission` command\. Replace the ARN and account ID with your own\. - - ``` - $ aws lambda add-permission --function-name CloudTrailEventProcessing \ - --statement-id Id-1 --action "lambda:InvokeFunction" --principal s3.amazonaws.com \ - --source-arn arn:aws:s3:::my-bucket \ - --source-account 123456789012 - ``` - - This command grants the Amazon S3 service principal \(`s3.amazonaws.com`\) permissions to perform the `lambda:InvokeFunction` action\. Invoke permissions are granted to Amazon S3 only if the following conditions are met: - + CloudTrail stores a log object in the specified bucket\. - + The bucket is owned by the specified AWS account\. If the bucket owner deletes a bucket, another AWS account can create a bucket with the same name\. This condition ensures that only the specified AWS account can invoke your Lambda function\. - -1. To view the Lambda function's access policy, run the following `get-policy` command, and replace the function name\. - - ``` - $ aws lambda get-policy --function-name function-name - ``` - -## Step 6: Configuring notifications on an Amazon S3 bucket - -To request that Amazon S3 publishes object\-created events to Lambda, add a notification configuration to the S3 bucket\. In the configuration, you specify the following: -+ Event type – Any event types that create objects\. -+ Lambda function – The Lambda function that you want Amazon S3 to invoke\. - -**To configure notifications** - -1. Open the [Amazon S3 console](https://console.aws.amazon.com/s3)\. - -1. Choose the source bucket\. - -1. Choose **Properties**\. - -1. Under **Events**, configure a notification with the following settings: - + **Name** – **lambda\-trigger** - + **Events** – **All object create events** - + **Send to** – **Lambda function** - + **Lambda** – **CloudTrailEventProcessing** - -When CloudTrail stores logs in the bucket, Amazon S3 sends an event to the function\. The event provides information, including the bucket name and key name of the log object that CloudTrail created\. \ No newline at end of file diff --git a/doc_source/with-cloudtrail.md b/doc_source/with-cloudtrail.md deleted file mode 100644 index 03e536f7..00000000 --- a/doc_source/with-cloudtrail.md +++ /dev/null @@ -1,84 +0,0 @@ -# Using AWS Lambda with AWS CloudTrail - -AWS CloudTrail is a service that provides a record of actions taken by a user, role, or an AWS service\. CloudTrail captures API calls as events\. For an ongoing record of events in your AWS account, you create a trail\. A trail enables CloudTrail to deliver log files of events to an Amazon S3 bucket\. - -You can take advantage of Amazon S3's bucket notification feature and direct Amazon S3 to publish object\-created events to AWS Lambda\. Whenever CloudTrail writes logs to your S3 bucket, Amazon S3 can then invoke your Lambda function by passing the Amazon S3 object\-created event as a parameter\. The S3 event provides information, including the bucket name and key name of the log object that CloudTrail created\. Your Lambda function code can read the log object and process the access records logged by CloudTrail\. For example, you might write Lambda function code to notify you if specific API call was made in your account\. - -In this scenario, CloudTrail writes access logs to your S3 bucket\. As for AWS Lambda, Amazon S3 is the event source so Amazon S3 publishes events to AWS Lambda and invokes your Lambda function\. - -**Example CloudTrail log** - -``` -{ - "Records":[ - { - "eventVersion":"1.02", - "userIdentity":{ - "type":"Root", - "principalId":"123456789012", - "arn":"arn:aws:iam::123456789012:root", - "accountId":"123456789012", - "accessKeyId":"access-key-id", - "sessionContext":{ - "attributes":{ - "mfaAuthenticated":"false", - "creationDate":"2015-01-24T22:41:54Z" - } - } - }, - "eventTime":"2015-01-24T23:26:50Z", - "eventSource":"sns.amazonaws.com", - "eventName":"CreateTopic", - "awsRegion":"us-east-2", - "sourceIPAddress":"205.251.233.176", - "userAgent":"console.amazonaws.com", - "requestParameters":{ - "name":"dropmeplease" - }, - "responseElements":{ - "topicArn":"arn:aws:sns:us-east-2:123456789012:exampletopic" - }, - "requestID":"3fdb7834-9079-557e-8ef2-350abc03536b", - "eventID":"17b46459-dada-4278-b8e2-5a4ca9ff1a9c", - "eventType":"AwsApiCall", - "recipientAccountId":"123456789012" - }, - { - "eventVersion":"1.02", - "userIdentity":{ - "type":"Root", - "principalId":"123456789012", - "arn":"arn:aws:iam::123456789012:root", - "accountId":"123456789012", - "accessKeyId": "AKIAIOSFODNN7EXAMPLE", - "sessionContext":{ - "attributes":{ - "mfaAuthenticated":"false", - "creationDate":"2015-01-24T22:41:54Z" - } - } - }, - "eventTime":"2015-01-24T23:27:02Z", - "eventSource":"sns.amazonaws.com", - "eventName":"GetTopicAttributes", - "awsRegion":"us-east-2", - "sourceIPAddress":"205.251.233.176", - "userAgent":"console.amazonaws.com", - "requestParameters":{ - "topicArn":"arn:aws:sns:us-east-2:123456789012:exampletopic" - }, - "responseElements":null, - "requestID":"4a0388f7-a0af-5df9-9587-c5c98c29cbec", - "eventID":"ec5bb073-8fa1-4d45-b03c-f07b9fc9ea18", - "eventType":"AwsApiCall", - "recipientAccountId":"123456789012" - } - ] -} -``` - -For detailed information about how to configure Amazon S3 as the event source, see [Using AWS Lambda with Amazon S3 events](with-s3.md)\. - -**Topics** -+ [Tutorial: Triggering a Lambda function with AWS CloudTrail events](with-cloudtrail-example.md) -+ [Sample function code](with-cloudtrail-create-package.md) \ No newline at end of file diff --git a/doc_source/with-ddb-create-package.md b/doc_source/with-ddb-create-package.md deleted file mode 100644 index c95f96eb..00000000 --- a/doc_source/with-ddb-create-package.md +++ /dev/null @@ -1,170 +0,0 @@ -# Sample function code - -Sample code is available for the following languages\. - -**Topics** -+ [Node\.js](#with-ddb-example-deployment-pkg-nodejs) -+ [Java 11](#with-ddb-example-deployment-pkg-java) -+ [C\#](#with-ddb-example-deployment-pkg-dotnet) -+ [Python 3](#with-ddb-example-deployment-pkg-python) -+ [Go](#with-ddb-example-deployment-pkg-go) - -## Node\.js - -The following example processes messages from DynamoDB, and logs their contents\. - -**Example ProcessDynamoDBStream\.js** - -``` -console.log('Loading function'); - -exports.lambda_handler = function(event, context, callback) { - console.log(JSON.stringify(event, null, 2)); - event.Records.forEach(function(record) { - console.log(record.eventID); - console.log(record.eventName); - console.log('DynamoDB Record: %j', record.dynamodb); - }); - callback(null, "message"); -}; -``` - -Zip up the sample code to create a deployment package\. For instructions, see [AWS Lambda deployment package in Node\.js](nodejs-package.md)\. - -## Java 11 - -The following example processes messages from DynamoDB, and logs their contents\. `handleRequest` is the handler that AWS Lambda invokes and provides event data\. The handler uses the predefined `DynamodbEvent` class, which is defined in the `aws-lambda-java-events` library\. - -**Example DDBEventProcessor\.java** - -``` -package example; - -import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.LambdaLogger; -import com.amazonaws.services.lambda.runtime.RequestHandler; -import com.amazonaws.services.lambda.runtime.events.DynamodbEvent; -import com.amazonaws.services.lambda.runtime.events.DynamodbEvent.DynamodbStreamRecord; - -public class DDBEventProcessor implements - RequestHandler { - - public String handleRequest(DynamodbEvent ddbEvent, Context context) { - for (DynamodbStreamRecord record : ddbEvent.getRecords()){ - System.out.println(record.getEventID()); - System.out.println(record.getEventName()); - System.out.println(record.getDynamodb().toString()); - - } - return "Successfully processed " + ddbEvent.getRecords().size() + " records."; - } -} -``` - -If the handler returns normally without exceptions, Lambda considers the input batch of records as processed successfully and begins reading new records in the stream\. If the handler throws an exception, Lambda considers the input batch of records as not processed and invokes the function with the same batch of records again\. - -**Dependencies** -+ `aws-lambda-java-core` -+ `aws-lambda-java-events` - -Build the code with the Lambda library dependencies to create a deployment package\. For instructions, see [AWS Lambda deployment package in Java](java-package.md)\. - -## C\# - -The following example processes messages from DynamoDB, and logs their contents\. `ProcessDynamoEvent` is the handler that AWS Lambda invokes and provides event data\. The handler uses the predefined `DynamoDbEvent` class, which is defined in the `Amazon.Lambda.DynamoDBEvents` library\. - -**Example ProcessingDynamoDBStreams\.cs** - -``` -using System; -using System.IO; -using System.Text; -using Amazon.Lambda.Core; -using Amazon.Lambda.DynamoDBEvents; - -using Amazon.Lambda.Serialization.Json; - -namespace DynamoDBStreams -{ - public class DdbSample - { - private static readonly JsonSerializer _jsonSerializer = new JsonSerializer(); - - public void ProcessDynamoEvent(DynamoDBEvent dynamoEvent) - { - Console.WriteLine($"Beginning to process {dynamoEvent.Records.Count} records..."); - - foreach (var record in dynamoEvent.Records) - { - Console.WriteLine($"Event ID: {record.EventID}"); - Console.WriteLine($"Event Name: {record.EventName}"); - - string streamRecordJson = SerializeObject(record.Dynamodb); - Console.WriteLine($"DynamoDB Record:"); - Console.WriteLine(streamRecordJson); - } - - Console.WriteLine("Stream processing complete."); - } - - private string SerializeObject(object streamRecord) - { - using (var ms = new MemoryStream()) - { - _jsonSerializer.Serialize(streamRecord, ms); - return Encoding.UTF8.GetString(ms.ToArray()); - } - } - } -} -``` - -Replace the `Program.cs` in a \.NET Core project with the above sample\. For instructions, see [AWS Lambda Deployment Package in C\#](csharp-package.md)\. - -## Python 3 - -The following example processes messages from DynamoDB, and logs their contents\. - -**Example ProcessDynamoDBStream\.py** - -``` -from __future__ import print_function - -def lambda_handler(event, context): - for record in event['Records']: - print(record['eventID']) - print(record['eventName']) - print('Successfully processed %s records.' % str(len(event['Records']))) -``` - -Zip up the sample code to create a deployment package\. For instructions, see [AWS Lambda deployment package in Python](python-package.md)\. - -## Go - -The following example processes messages from DynamoDB, and logs their contents\. - -**Example** - -``` -import ( - "strings" - - "github.com/aws/aws-lambda-go/events" -) - -func handleRequest(ctx context.Context, e events.DynamoDBEvent) { - - for _, record := range e.Records { - fmt.Printf("Processing request data for event ID %s, type %s.\n", record.EventID, record.EventName) - - // Print new values for attributes of type String - for name, value := range record.Change.NewImage { - if value.DataType() == events.DataTypeString { - fmt.Printf("Attribute name: %s, value: %s\n", name, value.String()) - } - } - } -} -``` - -Zip up the sample code to create a deployment package\. For instructions, see [AWS Lambda deployment package in Python](python-package.md)\. \ No newline at end of file diff --git a/doc_source/with-ddb-example.md b/doc_source/with-ddb-example.md deleted file mode 100644 index 4e1d089e..00000000 --- a/doc_source/with-ddb-example.md +++ /dev/null @@ -1,252 +0,0 @@ -# Tutorial: Using AWS Lambda with Amazon DynamoDB streams - - In this tutorial, you create a Lambda function to consume events from an Amazon DynamoDB stream\. - -## Prerequisites - -This tutorial assumes that you have some knowledge of basic Lambda operations and the Lambda console\. If you haven't already, follow the instructions in [Getting started with AWS Lambda](getting-started.md) to create your first Lambda function\. - -To follow the procedures in this guide, you will need a command line terminal or shell to run commands\. Commands are shown in listings preceded by a prompt symbol \($\) and the name of the current directory, when appropriate: - -``` -~/lambda-project$ this is a command -this is output -``` - -For long commands, an escape character \(`\`\) is used to split a command over multiple lines\. - -On Linux and macOS, use your preferred shell and package manager\. On Windows 10, you can [install the Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows\-integrated version of Ubuntu and Bash\. - -## Create the execution role - -Create the [execution role](lambda-intro-execution-role.md) that gives your function permission to access AWS resources\. - -**To create an execution role** - -1. Open the [roles page](https://console.aws.amazon.com/iam/home#/roles) in the IAM console\. - -1. Choose **Create role**\. - -1. Create a role with the following properties\. - + **Trusted entity** – Lambda\. - + **Permissions** – **AWSLambdaDynamoDBExecutionRole**\. - + **Role name** – **lambda\-dynamodb\-role**\. - -The **AWSLambdaDynamoDBExecutionRole** has the permissions that the function needs to read items from DynamoDB and write logs to CloudWatch Logs\. - -## Create the function - -The following example code receives a DynamoDB event input and processes the messages that it contains\. For illustration, the code writes some of the incoming event data to CloudWatch Logs\. - -**Note** -For sample code in other languages, see [Sample function code](with-ddb-create-package.md)\. - -**Example index\.js** - -``` -console.log('Loading function'); - -exports.handler = function(event, context, callback) { - console.log(JSON.stringify(event, null, 2)); - event.Records.forEach(function(record) { - console.log(record.eventID); - console.log(record.eventName); - console.log('DynamoDB Record: %j', record.dynamodb); - }); - callback(null, "message"); -}; -``` - -**To create the function** - -1. Copy the sample code into a file named `index.js`\. - -1. Create a deployment package\. - - ``` - $ zip function.zip index.js - ``` - -1. Create a Lambda function with the `create-function` command\. - - ``` - $ aws lambda create-function --function-name ProcessDynamoDBRecords \ - --zip-file fileb://function.zip --handler index.handler --runtime nodejs12.x \ - --role arn:aws:iam::123456789012:role/lambda-dynamodb-role - ``` - -## Test the Lambda function - -In this step, you invoke your Lambda function manually using the `invoke` AWS Lambda CLI command and the following sample DynamoDB event\. - -**Example input\.txt** - -``` -{ - "Records":[ - { - "eventID":"1", - "eventName":"INSERT", - "eventVersion":"1.0", - "eventSource":"aws:dynamodb", - "awsRegion":"us-east-1", - "dynamodb":{ - "Keys":{ - "Id":{ - "N":"101" - } - }, - "NewImage":{ - "Message":{ - "S":"New item!" - }, - "Id":{ - "N":"101" - } - }, - "SequenceNumber":"111", - "SizeBytes":26, - "StreamViewType":"NEW_AND_OLD_IMAGES" - }, - "eventSourceARN":"stream-ARN" - }, - { - "eventID":"2", - "eventName":"MODIFY", - "eventVersion":"1.0", - "eventSource":"aws:dynamodb", - "awsRegion":"us-east-1", - "dynamodb":{ - "Keys":{ - "Id":{ - "N":"101" - } - }, - "NewImage":{ - "Message":{ - "S":"This item has changed" - }, - "Id":{ - "N":"101" - } - }, - "OldImage":{ - "Message":{ - "S":"New item!" - }, - "Id":{ - "N":"101" - } - }, - "SequenceNumber":"222", - "SizeBytes":59, - "StreamViewType":"NEW_AND_OLD_IMAGES" - }, - "eventSourceARN":"stream-ARN" - }, - { - "eventID":"3", - "eventName":"REMOVE", - "eventVersion":"1.0", - "eventSource":"aws:dynamodb", - "awsRegion":"us-east-1", - "dynamodb":{ - "Keys":{ - "Id":{ - "N":"101" - } - }, - "OldImage":{ - "Message":{ - "S":"This item has changed" - }, - "Id":{ - "N":"101" - } - }, - "SequenceNumber":"333", - "SizeBytes":38, - "StreamViewType":"NEW_AND_OLD_IMAGES" - }, - "eventSourceARN":"stream-ARN" - } - ] -} -``` - -Execute the following `invoke` command\. - -``` -$ aws lambda invoke --function-name ProcessDynamoDBRecords --payload file://input.txt outputfile.txt -``` - -The function returns the string `message` in the response body\. - -Verify the output in the `outputfile.txt` file\. - -## Create a DynamoDB table with a stream enabled - -Create an Amazon DynamoDB table with a stream enabled\. - -**To create a DynamoDB table** - -1. Open the [DynamoDB console](https://console.aws.amazon.com/dynamodb)\. - -1. Choose **Create table**\. - -1. Create a table with the following settings\. - + **Table name** – **lambda\-dynamodb\-stream** - + **Primary key** – **id** \(string\) - -1. Choose **Create**\. - -**To enable streams** - -1. Open the [DynamoDB console](https://console.aws.amazon.com/dynamodb)\. - -1. Choose **Tables**\. - -1. Choose the **lambda\-dynamodb\-stream** table\. - -1. Under **Overview**, choose **Manage stream**\. - -1. Choose **Enable**\. - -Write down the stream ARN\. You need this in the next step when you associate the stream with your Lambda function\. For more information on enabling streams, see [Capturing table activity with DynamoDB Streams](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html)\. - -## Add an event source in AWS Lambda - -Create an event source mapping in AWS Lambda\. This event source mapping associates the DynamoDB stream with your Lambda function\. After you create this event source mapping, AWS Lambda starts polling the stream\. - -Run the following AWS CLI `create-event-source-mapping` command\. After the command executes, note down the UUID\. You'll need this UUID to refer to the event source mapping in any commands, for example, when deleting the event source mapping\. - -``` -$ aws lambda create-event-source-mapping --function-name ProcessDynamoDBRecords \ - --batch-size 100 --starting-position LATEST --event-source DynamoDB-stream-arn -``` - - This creates a mapping between the specified DynamoDB stream and the Lambda function\. You can associate a DynamoDB stream with multiple Lambda functions, and associate the same Lambda function with multiple streams\. However, the Lambda functions will share the read throughput for the stream they share\. - -You can get the list of event source mappings by running the following command\. - -``` -$ aws lambda list-event-source-mappings -``` - -The list returns all of the event source mappings you created, and for each mapping it shows the `LastProcessingResult`, among other things\. This field is used to provide an informative message if there are any problems\. Values such as `No records processed` \(indicates that AWS Lambda has not started polling or that there are no records in the stream\) and `OK` \(indicates AWS Lambda successfully read records from the stream and invoked your Lambda function\) indicate that there are no issues\. If there are issues, you receive an error message\. - -If you have a lot of event source mappings, use the function name parameter to narrow down the results\. - -``` -$ aws lambda list-event-source-mappings --function-name ProcessDynamoDBRecords -``` - -## Test the setup - -Test the end\-to\-end experience\. As you perform table updates, DynamoDB writes event records to the stream\. As AWS Lambda polls the stream, it detects new records in the stream and executes your Lambda function on your behalf by passing events to the function\. - -1. In the DynamoDB console, add, update, and delete items to the table\. DynamoDB writes records of these actions to the stream\. - -1. AWS Lambda polls the stream and when it detects updates to the stream, it invokes your Lambda function by passing in the event data it finds in the stream\. - -1. Your function executes and creates logs in Amazon CloudWatch\. You can verify the logs reported in the Amazon CloudWatch console\. \ No newline at end of file diff --git a/doc_source/with-ddb.md b/doc_source/with-ddb.md deleted file mode 100644 index 3fa752b7..00000000 --- a/doc_source/with-ddb.md +++ /dev/null @@ -1,298 +0,0 @@ -# Using AWS Lambda with Amazon DynamoDB - -You can use an AWS Lambda function to process records in an [Amazon DynamoDB stream](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html)\. With DynamoDB Streams, you can trigger a Lambda function to perform additional work each time a DynamoDB table is updated\. - -Lambda reads records from the stream and invokes your function [synchronously](invocation-sync.md) with an event that contains stream records\. Lambda reads records in batches and invokes your function to process records from the batch\. - -**Example DynamoDB Streams record event** - -``` -{ - "Records": [ - { - "eventID": "1", - "eventVersion": "1.0", - "dynamodb": { - "Keys": { - "Id": { - "N": "101" - } - }, - "NewImage": { - "Message": { - "S": "New item!" - }, - "Id": { - "N": "101" - } - }, - "StreamViewType": "NEW_AND_OLD_IMAGES", - "SequenceNumber": "111", - "SizeBytes": 26 - }, - "awsRegion": "us-west-2", - "eventName": "INSERT", - "eventSourceARN": eventsourcearn, - "eventSource": "aws:dynamodb" - }, - { - "eventID": "2", - "eventVersion": "1.0", - "dynamodb": { - "OldImage": { - "Message": { - "S": "New item!" - }, - "Id": { - "N": "101" - } - }, - "SequenceNumber": "222", - "Keys": { - "Id": { - "N": "101" - } - }, - "SizeBytes": 59, - "NewImage": { - "Message": { - "S": "This item has changed" - }, - "Id": { - "N": "101" - } - }, - "StreamViewType": "NEW_AND_OLD_IMAGES" - }, - "awsRegion": "us-west-2", - "eventName": "MODIFY", - "eventSourceARN": sourcearn, - "eventSource": "aws:dynamodb" - } -``` - -Lambda polls shards in your DynamoDB stream for records at a base rate of 4 times per second\. When records are available, Lambda invokes your function and waits for the result\. If processing succeeds, Lambda resumes polling until it receives more records\. - -By default, Lambda invokes your function as soon as records are available in the stream\. If the batch it reads from the stream only has one record in it, Lambda only sends one record to the function\. To avoid invoking the function with a small number of records, you can tell the event source to buffer records for up to 5 minutes by configuring a *batch window*\. Before invoking the function, Lambda continues to read records from the stream until it has gathered a full batch, or until the batch window expires\. - -If your function returns an error, Lambda retries the batch until processing succeeds or the data expires\. To avoid stalled shards, you can configure the event source mapping to retry with a smaller batch size, limit the number of retries, or discard records that are too old\. To retain discarded events, you can configure the event source mapping to send details about failed batches to an SQS queue or SNS topic\. - -You can also increase concurrency by processing multiple batches from each shard in parallel\. Lambda can process up to 10 batches in each shard simultaneously\. If you increase the number of concurrent batches per shard, Lambda still ensures in\-order processing at the partition\-key level\. - -**Topics** -+ [Execution role permissions](#events-dynamodb-permissions) -+ [Configuring a stream as an event source](#services-dynamodb-eventsourcemapping) -+ [Event source mapping APIs](#services-dynamodb-api) -+ [Error handling](#services-dynamodb-errors) -+ [Amazon CloudWatch metrics](#events-dynamodb-metrics) -+ [Tutorial: Using AWS Lambda with Amazon DynamoDB streams](with-ddb-example.md) -+ [Sample function code](with-ddb-create-package.md) -+ [AWS SAM template for a DynamoDB application](kinesis-tutorial-spec.md) - -## Execution role permissions - -Lambda needs the following permissions to manage resources related to your DynamoDB stream\. Add them to your function's execution role\. -+ [dynamodb:DescribeStream](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_streams_DescribeStream.html) -+ [dynamodb:GetRecords](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_streams_GetRecords.html) -+ [dynamodb:GetShardIterator](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_streams_GetShardIterator.html) -+ [dynamodb:ListStreams](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_streams_ListStreams.html) - -The `AWSLambdaDynamoDBExecutionRole` managed policy includes these permissions\. For more information, see [AWS Lambda execution role](lambda-intro-execution-role.md)\. - -To send records of failed batches to a queue or topic, your function needs additional permissions\. Each destination service requires a different permission, as follows: -+ **Amazon SQS** – [sqs:SendMessage](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SendMessage.html) -+ **Amazon SNS** – [sns:Publish](https://docs.aws.amazon.com/sns/latest/api/API_Publish.html) - -## Configuring a stream as an event source - -Create an event source mapping to tell Lambda to send records from your stream to a Lambda function\. You can create multiple event source mappings to process the same data with multiple Lambda functions, or to process items from multiple streams with a single function\. - -To configure your function to read from DynamoDB Streams in the Lambda console, create a **DynamoDB** trigger\. - -**To create a trigger** - -1. Open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions)\. - -1. Choose a function\. - -1. Under **Designer**, choose **Add trigger**\. - -1. Choose a trigger type\. - -1. Configure the required options and then choose **Add**\. - -Lambda supports the following options for DynamoDB event sources\. - -**Event source options** -+ **DynamoDB table** – The DynamoDB table to read records from\. -+ **Batch size** – The number of records to send to the function in each batch, up to 1,000\. Lambda passes all of the records in the batch to the function in a single call, as long as the total size of the events doesn't exceed the [payload limit](gettingstarted-limits.md) for synchronous invocation \(6 MB\)\. -+ **Batch window** – Specify the maximum amount of time to gather records before invoking the function, in seconds\. -+ **Starting position** – Process only new records, or all existing records\. - + **Latest** – Process new records that are added to the stream\. - + **Trim horizon** – Process all records in the stream\. - - After processing any existing records, the function is caught up and continues to process new records\. -+ **On\-failure destination** – An SQS queue or SNS topic for records that can't be processed\. When Lambda discards a batch of records because it's too old or has exhausted all retries, it sends details about the batch to the queue or topic\. -+ **Retry attempts** – The maximum number of times that Lambda retries when the function returns an error\. This doesn't apply to service errors or throttles where the batch didn't reach the function\. -+ **Maximum age of record** – The maximum age of a record that Lambda sends to your function\. -+ **Split batch on error** – When the function returns an error, split the batch into two before retrying\. -+ **Concurrent batches per shard** – Process multiple batches from the same shard concurrently\. -+ **Enabled** – Disable the event source to stop processing records\. Lambda keeps track of the last record processed and resumes processing from that point when the mapping is reenabled\. - -To manage the event source configuration later, choose the trigger in the designer\. - -## Event source mapping APIs - -To manage event source mappings with the AWS CLI or AWS SDK, use the following API actions: -+ [CreateEventSourceMapping](API_CreateEventSourceMapping.md) -+ [ListEventSourceMappings](API_ListEventSourceMappings.md) -+ [GetEventSourceMapping](API_GetEventSourceMapping.md) -+ [UpdateEventSourceMapping](API_UpdateEventSourceMapping.md) -+ [DeleteEventSourceMapping](API_DeleteEventSourceMapping.md) - -The following example uses the AWS CLI to map a function named `my-function` to a DynamoDB stream that is specified by its Amazon Resource Name \(ARN\), with a batch size of 500\. - -``` -$ aws lambda create-event-source-mapping --function-name my-function --batch-size 500 --starting-position LATEST \ ---event-source-arn arn:aws:dynamodb:us-east-2:123456789012:table/my-table/stream/2019-06-10T19:26:16.525 -{ - "UUID": "14e0db71-5d35-4eb5-b481-8945cf9d10c2", - "BatchSize": 500, - "MaximumBatchingWindowInSeconds": 0, - "ParallelizationFactor": 1, - "EventSourceArn": "arn:aws:dynamodb:us-east-2:123456789012:table/my-table/stream/2019-06-10T19:26:16.525", - "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function", - "LastModified": 1560209851.963, - "LastProcessingResult": "No records processed", - "State": "Creating", - "StateTransitionReason": "User action", - "DestinationConfig": {}, - "MaximumRecordAgeInSeconds": 604800, - "BisectBatchOnFunctionError": false, - "MaximumRetryAttempts": 10000 -} -``` - -Configure additional options to customize how batches are processed and to specify when to discard records that can't be processed\. The following example updates an event source mapping to send a failure record to an SQS queue after two retry attempts, or if the records are more than an hour old\. - -``` -$ aws lambda update-event-source-mapping --uuid f89f8514-cdd9-4602-9e1f-01a5b77d449b \ ---maximum-retry-attempts 2 --maximum-record-age-in-seconds 3600 ---destination-config '{"OnFailure": {"Destination": "arn:aws:sqs:us-east-2:123456789012:dlq"}}' -{ - "UUID": "f89f8514-cdd9-4602-9e1f-01a5b77d449b", - "BatchSize": 100, - "MaximumBatchingWindowInSeconds": 0, - "ParallelizationFactor": 1, - "EventSourceArn": "arn:aws:dynamodb:us-east-2:123456789012:table/my-table/stream/2019-06-10T19:26:16.525", - "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function", - "LastModified": 1573243620.0, - "LastProcessingResult": "PROBLEM: Function call failed", - "State": "Updating", - "StateTransitionReason": "User action", - "DestinationConfig": {}, - "MaximumRecordAgeInSeconds": 604800, - "BisectBatchOnFunctionError": false, - "MaximumRetryAttempts": 10000 -} -``` - -Updated settings are applied asynchronously and aren't reflected in the output until the process completes\. Use the `get-event-source-mapping` command to view the current status\. - -``` -$ aws lambda get-event-source-mapping --uuid f89f8514-cdd9-4602-9e1f-01a5b77d449b -{ - "UUID": "f89f8514-cdd9-4602-9e1f-01a5b77d449b", - "BatchSize": 100, - "MaximumBatchingWindowInSeconds": 0, - "ParallelizationFactor": 1, - "EventSourceArn": "arn:aws:dynamodb:us-east-2:123456789012:table/my-table/stream/2019-06-10T19:26:16.525", - "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function", - "LastModified": 1573244760.0, - "LastProcessingResult": "PROBLEM: Function call failed", - "State": "Enabled", - "StateTransitionReason": "User action", - "DestinationConfig": { - "OnFailure": { - "Destination": "arn:aws:sqs:us-east-2:123456789012:dlq" - } - }, - "MaximumRecordAgeInSeconds": 3600, - "BisectBatchOnFunctionError": false, - "MaximumRetryAttempts": 2 -} -``` - -To process multiple batches concurrently, use the `--parallelization-factor` option\. - -``` -$ aws lambda update-event-source-mapping --uuid 2b733gdc-8ac3-cdf5-af3a-1827b3b11284 \ ---parallelization-factor 5 -``` - -## Error handling - -The event source mapping that reads records from your DynamoDB stream invokes your function synchronously and retries on errors\. If the function is throttled or the Lambda service returns an error without invoking the function, Lambda retries until the records expire or exceed the maximum age that you configure on the event source mapping\. - -If the function receives the records but returns an error, Lambda retries until the records in the batch expire, exceed the maximum age, or reach the configured retry limit\. For function errors, you can also configure the event source mapping to split a failed batch into two batches\. Retrying with smaller batches isolates bad records and works around timeout issues\. Splitting a batch does not count towards the retry limit\. - -If the error handling measures fail, Lambda discards the records and continues processing batches from the stream\. With the default settings, this means that a bad record can block processing on the affected shard for up to one day\. To avoid this, configure your function's event source mapping with a reasonable number of retries and a maximum record age that fits your use case\. - -To retain a record of discarded batches, configure a failed\-event destination\. Lambda sends a document to the destination queue or topic with details about the batch\. - -**To configure a destination for failed\-event records** - -1. Open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions)\. - -1. Choose a function\. - -1. Under **Designer**, choose **Add destination**\. - -1. For **Source**, choose **Stream invocation**\. - -1. For **Stream**, choose a stream that is mapped to the function\. - -1. For **Destination type**, choose the type of resource that receives the invocation record\. - -1. For **Destination**, choose a resource\. - -1. Choose **Save**\. - -The following example shows an invocation record for a DynamoDB stream\. - -**Example Invocation Record** - -``` -{ - "requestContext": { - "requestId": "316aa6d0-8154-xmpl-9af7-85d5f4a6bc81", - "functionArn": "arn:aws:lambda:us-east-2:123456789012:function:myfunction", - "condition": "RetryAttemptsExhausted", - "approximateInvokeCount": 1 - }, - "responseContext": { - "statusCode": 200, - "executedVersion": "$LATEST", - "functionError": "Unhandled" - }, - "version": "1.0", - "timestamp": "2019-11-14T00:13:49.717Z", - "DDBStreamBatchInfo": { - "shardId": "shardId-00000001573689847184-864758bb", - "startSequenceNumber": "800000000003126276362", - "endSequenceNumber": "800000000003126276362", - "approximateArrivalOfFirstRecord": "2019-11-14T00:13:19Z", - "approximateArrivalOfLastRecord": "2019-11-14T00:13:19Z", - "batchSize": 1, - "streamArn": "arn:aws:dynamodb:us-east-2:123456789012:table/mytable/stream/2019-11-14T00:04:06.388" - } -} -``` - -You can use this information to retrieve the affected records from the stream for troubleshooting\. The actual records aren't included, so you must process this record and retrieve them from the stream before they expire and are lost\. - -## Amazon CloudWatch metrics - -Lambda emits the `IteratorAge` metric when your function finishes processing a batch of records\. The metric indicates how old the last record in the batch was when processing finished\. If your function is processing new events, you can use the iterator age to estimate the latency between when a record is added and when the function processes it\. - -An increasing trend in iterator age can indicate issues with your function\. For more information, see [Working with AWS Lambda function metrics](monitoring-metrics.md)\. \ No newline at end of file diff --git a/doc_source/with-kinesis-create-package.md b/doc_source/with-kinesis-create-package.md deleted file mode 100644 index 4dd15693..00000000 --- a/doc_source/with-kinesis-create-package.md +++ /dev/null @@ -1,166 +0,0 @@ -# Sample function code - -To process events from Amazon Kinesis, iterate through the records included in the event object and decode the Base64\-encoded data included in each\. - -**Note** -The code on this page does not support [aggregated records](https://docs.aws.amazon.com/kinesis/latest/dev/kinesis-kpl-concepts.html#kinesis-kpl-concepts-aggretation)\. You can disable aggregation in the Kinesis Producer Library [configuration](https://docs.aws.amazon.com/kinesis/latest/dev/kinesis-kpl-config.html), or use the [Kinesis Record Aggregation library](https://github.com/awslabs/kinesis-aggregation) to deaggregate records\. - -Sample code is available for the following languages\. - -**Topics** -+ [Node\.js 8](#with-kinesis-example-deployment-pkg-nodejs) -+ [Java 11](#with-kinesis-example-deployment-pkg-java) -+ [C\#](#with-kinesis-example-deployment-pkg-dotnet) -+ [Python 3](#with-kinesis-example-deployment-pkg-python) -+ [Go](#with-kinesis-example-deployment-pkg-go) - -## Node\.js 8 - -The following example code receives a Kinesis event input and processes the messages that it contains\. For illustration, the code writes some of the incoming event data to CloudWatch Logs\. - -**Example index\.js** - -``` -console.log('Loading function'); - -exports.handler = function(event, context) { - //console.log(JSON.stringify(event, null, 2)); - event.Records.forEach(function(record) { - // Kinesis data is base64 encoded so decode here - var payload = Buffer.from(record.kinesis.data, 'base64').toString('ascii'); - console.log('Decoded payload:', payload); - }); -}; -``` - -Zip up the sample code to create a deployment package\. For instructions, see [AWS Lambda deployment package in Node\.js](nodejs-package.md)\. - -## Java 11 - -The following is example Java code that receives Kinesis event record data as input and processes it\. For illustration, the code writes some of the incoming event data to CloudWatch Logs\. - -In the code, `recordHandler` is the handler\. The handler uses the predefined `KinesisEvent` class that is defined in the `aws-lambda-java-events` library\. - -**Example ProcessKinesisEvents\.java** - -``` -package example; - -import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; -import com.amazonaws.services.lambda.runtime.events.KinesisEvent; -import com.amazonaws.services.lambda.runtime.events.KinesisEvent.KinesisEventRecord; - -public class ProcessKinesisRecords implements RequestHandler{ - @Override - public Void handleRequest(KinesisEvent event, Context context) - { - for(KinesisEventRecord rec : event.getRecords()) { - System.out.println(new String(rec.getKinesis().getData().array())); - } - return null; - } -} -``` - -If the handler returns normally without exceptions, Lambda considers the input batch of records as processed successfully and begins reading new records in the stream\. If the handler throws an exception, Lambda considers the input batch of records as not processed and invokes the function with the same batch of records again\. - -**Dependencies** -+ `aws-lambda-java-core` -+ `aws-lambda-java-events` -+ `aws-java-sdk` - -Build the code with the Lambda library dependencies to create a deployment package\. For instructions, see [AWS Lambda deployment package in Java](java-package.md)\. - -## C\# - -The following is example C\# code that receives Kinesis event record data as input and processes it\. For illustration, the code writes some of the incoming event data to CloudWatch Logs\. - - In the code, `HandleKinesisRecord` is the handler\. The handler uses the predefined `KinesisEvent` class that is defined in the `Amazon.Lambda.KinesisEvents` library\. - -**Example ProcessingKinesisEvents\.cs** - -``` -using System; -using System.IO; -using System.Text; - -using Amazon.Lambda.Core; -using Amazon.Lambda.KinesisEvents; - -namespace KinesisStreams -{ - public class KinesisSample - { - [LambdaSerializer(typeof(JsonSerializer))] - public void HandleKinesisRecord(KinesisEvent kinesisEvent) - { - Console.WriteLine($"Beginning to process {kinesisEvent.Records.Count} records..."); - - foreach (var record in kinesisEvent.Records) - { - Console.WriteLine($"Event ID: {record.EventId}"); - Console.WriteLine($"Event Name: {record.EventName}"); - - string recordData = GetRecordContents(record.Kinesis); - Console.WriteLine($"Record Data:"); - Console.WriteLine(recordData); - } - Console.WriteLine("Stream processing complete."); - } - - private string GetRecordContents(KinesisEvent.Record streamRecord) - { - using (var reader = new StreamReader(streamRecord.Data, Encoding.ASCII)) - { - return reader.ReadToEnd(); - } - } - } -} -``` -Replace the `Program.cs` in a \.NET Core project with the above sample\. For instructions, see [AWS Lambda Deployment Package in C\#](csharp-package.md)\. - -## Python 3 - - The following is example Python code that receives Kinesis event record data as input and processes it\. For illustration, the code writes to some of the incoming event data to CloudWatch Logs\. - -**Example ProcessKinesisRecords\.py** - -``` -from __future__ import print_function -#import json -import base64 -def lambda_handler(event, context): - for record in event['Records']: - #Kinesis data is base64 encoded so decode here - payload=base64.b64decode(record["kinesis"]["data"]) - print("Decoded payload: " + str(payload)) -``` - -Zip up the sample code to create a deployment package\. For instructions, see [AWS Lambda deployment package in Python](python-package.md)\. - -## Go - - The following is example Go code that receives Kinesis event record data as input and processes it\. For illustration, the code writes to some of the incoming event data to CloudWatch Logs\. - -**Example ProcessKinesisRecords\.go** - -``` -import ( - "strings" - "github.com/aws/aws-lambda-go/events" -) - -func handler(ctx context.Context, kinesisEvent events.KinesisEvent) { - for _, record := range kinesisEvent.Records { - kinesisRecord := record.Kinesis - dataBytes := kinesisRecord.Data - dataText := string(dataBytes) - - fmt.Printf("%s Data = %s \n", record.EventName, dataText) - } -} -``` - -Build the executable with `go build` and create a deployment package\. For instructions, see [AWS Lambda deployment package in Go](golang-package.md)\. \ No newline at end of file diff --git a/doc_source/with-kinesis-example-use-app-spec.md b/doc_source/with-kinesis-example-use-app-spec.md deleted file mode 100644 index 28b3e4b8..00000000 --- a/doc_source/with-kinesis-example-use-app-spec.md +++ /dev/null @@ -1,86 +0,0 @@ -# AWS SAM template for a Kinesis application - -You can build this application using [AWS SAM](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/)\. To learn more about creating AWS SAM templates, see [AWS SAM template basics](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-template-basics.html) in the *AWS Serverless Application Model Developer Guide*\. - -Below is a sample AWS SAM template for the Lambda application from the [tutorial](with-kinesis-example.md)\. The function and handler in the template are for the Node\.js code\. If you use a different code sample, update the values accordingly\. - -**Example template\.yaml \- Kinesis stream** - -``` -AWSTemplateFormatVersion: '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Resources: - LambdaFunction: - Type: AWS::Serverless::Function - Properties: - Handler: index.handler - Runtime: nodejs12.x - Timeout: 10 - Tracing: Active - Events: - Stream: - Type: Kinesis - Properties: - Stream: !GetAtt stream.Arn - BatchSize: 100 - StartingPosition: LATEST - stream: - Type: AWS::Kinesis::Stream - Properties: - ShardCount: 1 -Outputs: - FunctionName: - Description: "Function name" - Value: !Ref LambdaFunction - StreamARN: - Description: "Stream ARN" - Value: !GetAtt stream.Arn -``` - -The template creates a Lambda function, a Kinesis stream, and an event source mapping\. The event source mapping reads from the stream and invokes the function\. - -To use an [HTTP/2 stream consumer](with-kinesis.md#services-kinesis-configure), create the consumer in the template and configure the event source mapping to read from the consumer instead of from the stream\. - -**Example template\.yaml \- Kinesis stream consumer** - -``` -AWSTemplateFormatVersion: '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Description: A function that processes data from a Kinesis stream. -Resources: - function: - Type: AWS::Serverless::Function - Properties: - Handler: index.handler - Runtime: nodejs12.x - Timeout: 10 - Tracing: Active - Events: - Stream: - Type: Kinesis - Properties: - Stream: !GetAtt streamConsumer.ConsumerARN - StartingPosition: LATEST - BatchSize: 100 - stream: - Type: "AWS::Kinesis::Stream" - Properties: - ShardCount: 1 - streamConsumer: - Type: "AWS::Kinesis::StreamConsumer" - Properties: - StreamARN: !GetAtt stream.Arn - ConsumerName: "TestConsumer" -Outputs: - FunctionName: - Description: "Function name" - Value: !Ref function - StreamARN: - Description: "Stream ARN" - Value: !GetAtt stream.Arn - ConsumerARN: - Description: "Stream consumer ARN" - Value: !GetAtt streamConsumer.ConsumerARN -``` - -For information on how to package and deploy your serverless application using the package and deploy commands, see [Deploying serverless applications](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-deploying.html) in the *AWS Serverless Application Model Developer Guide*\. \ No newline at end of file diff --git a/doc_source/with-kinesis-example.md b/doc_source/with-kinesis-example.md deleted file mode 100644 index bef0450e..00000000 --- a/doc_source/with-kinesis-example.md +++ /dev/null @@ -1,196 +0,0 @@ -# Tutorial: Using AWS Lambda with Amazon Kinesis - -In this tutorial, you create a Lambda function to consume events from a Kinesis stream\. The following diagram illustrates the application flow: - -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/kinesis-pull-10.png) - -1. Custom app writes records to the stream\. - -1. AWS Lambda polls the stream and, when it detects new records in the stream, invokes your Lambda function\. - -1. AWS Lambda executes the Lambda function by assuming the execution role you specified at the time you created the Lambda function\. - -## Prerequisites - -This tutorial assumes that you have some knowledge of basic Lambda operations and the Lambda console\. If you haven't already, follow the instructions in [Getting started with AWS Lambda](getting-started.md) to create your first Lambda function\. - -To follow the procedures in this guide, you will need a command line terminal or shell to run commands\. Commands are shown in listings preceded by a prompt symbol \($\) and the name of the current directory, when appropriate: - -``` -~/lambda-project$ this is a command -this is output -``` - -For long commands, an escape character \(`\`\) is used to split a command over multiple lines\. - -On Linux and macOS, use your preferred shell and package manager\. On Windows 10, you can [install the Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows\-integrated version of Ubuntu and Bash\. - -## Create the execution role - -Create the [execution role](lambda-intro-execution-role.md) that gives your function permission to access AWS resources\. - -**To create an execution role** - -1. Open the [roles page](https://console.aws.amazon.com/iam/home#/roles) in the IAM console\. - -1. Choose **Create role**\. - -1. Create a role with the following properties\. - + **Trusted entity** – **AWS Lambda**\. - + **Permissions** – **AWSLambdaKinesisExecutionRole**\. - + **Role name** – **lambda\-kinesis\-role**\. - -The **AWSLambdaKinesisExecutionRole** policy has the permissions that the function needs to read items from Kinesis and write logs to CloudWatch Logs\. - -## Create the function - -The following example code receives a Kinesis event input and processes the messages that it contains\. For illustration, the code writes some of the incoming event data to CloudWatch Logs\. - -**Note** -For sample code in other languages, see [Sample function code](with-kinesis-create-package.md)\. - -**Example index\.js** - -``` -console.log('Loading function'); - -exports.handler = function(event, context) { - //console.log(JSON.stringify(event, null, 2)); - event.Records.forEach(function(record) { - // Kinesis data is base64 encoded so decode here - var payload = Buffer.from(record.kinesis.data, 'base64').toString('ascii'); - console.log('Decoded payload:', payload); - }); -}; -``` - -**To create the function** - -1. Copy the sample code into a file named `index.js`\. - -1. Create a deployment package\. - - ``` - $ zip function.zip index.js - ``` - -1. Create a Lambda function with the `create-function` command\. - - ``` - $ aws lambda create-function --function-name ProcessKinesisRecords \ - --zip-file fileb://function.zip --handler index.handler --runtime nodejs12.x \ - --role arn:aws:iam::123456789012:role/lambda-kinesis-role - ``` - -## Test the Lambda function - -Invoke your Lambda function manually using the `invoke` AWS Lambda CLI command and a sample Kinesis event\. - -**To test the Lambda function** - -1. Copy the following JSON into a file and save it as `input.txt`\. - - ``` - { - "Records": [ - { - "kinesis": { - "kinesisSchemaVersion": "1.0", - "partitionKey": "1", - "sequenceNumber": "49590338271490256608559692538361571095921575989136588898", - "data": "SGVsbG8sIHRoaXMgaXMgYSB0ZXN0Lg==", - "approximateArrivalTimestamp": 1545084650.987 - }, - "eventSource": "aws:kinesis", - "eventVersion": "1.0", - "eventID": "shardId-000000000006:49590338271490256608559692538361571095921575989136588898", - "eventName": "aws:kinesis:record", - "invokeIdentityArn": "arn:aws:iam::123456789012:role/lambda-kinesis-role", - "awsRegion": "us-east-2", - "eventSourceARN": "arn:aws:kinesis:us-east-2:123456789012:stream/lambda-stream" - } - ] - } - ``` - -1. Use the `invoke` command to send the event to the function\. - - ``` - $ aws lambda invoke --function-name ProcessKinesisRecords --payload file://input.txt out.txt - ``` - - The response is saved to `out.txt`\. - -## Create a Kinesis stream - -Use the `create-stream ` command to create a stream\. - -``` -$ aws kinesis create-stream --stream-name lambda-stream --shard-count 1 -``` - -Run the following `describe-stream` command to get the stream ARN\. - -``` -$ aws kinesis describe-stream --stream-name lambda-stream -{ - "StreamDescription": { - "Shards": [ - { - "ShardId": "shardId-000000000000", - "HashKeyRange": { - "StartingHashKey": "0", - "EndingHashKey": "340282366920746074317682119384634633455" - }, - "SequenceNumberRange": { - "StartingSequenceNumber": "49591073947768692513481539594623130411957558361251844610" - } - } - ], - "StreamARN": "arn:aws:kinesis:us-west-2:123456789012:stream/lambda-stream", - "StreamName": "lambda-stream", - "StreamStatus": "ACTIVE", - "RetentionPeriodHours": 24, - "EnhancedMonitoring": [ - { - "ShardLevelMetrics": [] - } - ], - "EncryptionType": "NONE", - "KeyId": null, - "StreamCreationTimestamp": 1544828156.0 - } -} -``` - -You use the stream ARN in the next step to associate the stream with your Lambda function\. - -## Add an event source in AWS Lambda - -Run the following AWS CLI `add-event-source` command\. - -``` -$ aws lambda create-event-source-mapping --function-name ProcessKinesisRecords \ ---event-source arn:aws:kinesis:us-west-2:123456789012:stream/lambda-stream \ ---batch-size 100 --starting-position LATEST -``` - -Note the mapping ID for later use\. You can get a list of event source mappings by running the `list-event-source-mappings` command\. - -``` -$ aws lambda list-event-source-mappings --function-name ProcessKinesisRecords \ ---event-source arn:aws:kinesis:us-west-2:123456789012:stream/lambda-stream -``` - -In the response, you can verify the status value is `enabled`\. Event source mappings can be disabled to pause polling temporarily without losing any records\. - -## Test the setup - -To test the event source mapping, add event records to your Kinesis stream\. The `--data` value is a string that the CLI encodes to base64 prior to sending it to Kinesis\. You can run the same command more than once to add multiple records to the stream\. - -``` -$ aws kinesis put-record --stream-name lambda-stream --partition-key 1 \ ---data "Hello, this is a test." -``` - -Lambda uses the execution role to read records from the stream\. Then it invokes your Lambda function, passing in batches of records\. The function decodes data from each record and logs it, sending the output to CloudWatch Logs\. View the logs in the [CloudWatch console](https://console.aws.amazon.com/cloudwatch)\. \ No newline at end of file diff --git a/doc_source/with-kinesis.md b/doc_source/with-kinesis.md deleted file mode 100644 index c601ce47..00000000 --- a/doc_source/with-kinesis.md +++ /dev/null @@ -1,311 +0,0 @@ -# Using AWS Lambda with Amazon Kinesis - -You can use an AWS Lambda function to process records in an [Amazon Kinesis data stream](https://docs.aws.amazon.com/kinesis/latest/dev/amazon-kinesis-streams.html)\. With Kinesis, you can collect data from many sources and process them with multiple consumers\. Lambda supports standard data stream iterators and HTTP/2 stream consumers\. - -Lambda reads records from the data stream and invokes your function [synchronously](invocation-sync.md) with an event that contains stream records\. Lambda reads records in batches and invokes your function to process records from the batch\. - -**Example Kinesis record event** - -``` -{ - "Records": [ - { - "kinesis": { - "kinesisSchemaVersion": "1.0", - "partitionKey": "1", - "sequenceNumber": "49590338271490256608559692538361571095921575989136588898", - "data": "SGVsbG8sIHRoaXMgaXMgYSB0ZXN0Lg==", - "approximateArrivalTimestamp": 1545084650.987 - }, - "eventSource": "aws:kinesis", - "eventVersion": "1.0", - "eventID": "shardId-000000000006:49590338271490256608559692538361571095921575989136588898", - "eventName": "aws:kinesis:record", - "invokeIdentityArn": "arn:aws:iam::123456789012:role/lambda-role", - "awsRegion": "us-east-2", - "eventSourceARN": "arn:aws:kinesis:us-east-2:123456789012:stream/lambda-stream" - }, - { - "kinesis": { - "kinesisSchemaVersion": "1.0", - "partitionKey": "1", - "sequenceNumber": "49590338271490256608559692540925702759324208523137515618", - "data": "VGhpcyBpcyBvbmx5IGEgdGVzdC4=", - "approximateArrivalTimestamp": 1545084711.166 - }, - "eventSource": "aws:kinesis", - "eventVersion": "1.0", - "eventID": "shardId-000000000006:49590338271490256608559692540925702759324208523137515618", - "eventName": "aws:kinesis:record", - "invokeIdentityArn": "arn:aws:iam::123456789012:role/lambda-role", - "awsRegion": "us-east-2", - "eventSourceARN": "arn:aws:kinesis:us-east-2:123456789012:stream/lambda-stream" - } - ] -} -``` - -If you have multiple applications that are reading records from the same stream, you can use Kinesis stream consumers instead of standard iterators\. Consumers have dedicated read throughput so they don't have to compete with other consumers of the same data\. With consumers, Kinesis pushes records to Lambda over an HTTP/2 connection, which can also reduce latency between adding a record and function invocation\. - -**Note** -Batch window, error handling, and concurrency settings are not available for HTTP/2 stream consumers\. - -By default, Lambda invokes your function as soon as records are available in the stream\. If the batch it reads from the stream only has one record in it, Lambda only sends one record to the function\. To avoid invoking the function with a small number of records, you can tell the event source to buffer records for up to 5 minutes by configuring a *batch window*\. Before invoking the function, Lambda continues to read records from the stream until it has gathered a full batch, or until the batch window expires\. - -If your function returns an error, Lambda retries the batch until processing succeeds or the data expires\. To avoid stalled shards, you can configure the event source mapping to retry with a smaller batch size, limit the number of retries, or discard records that are too old\. To retain discarded events, you can configure the event source mapping to send details about failed batches to an SQS queue or SNS topic\. - -You can also increase concurrency by processing multiple batches from each shard in parallel\. Lambda can process up to 10 batches in each shard simultaneously\. If you increase the number of concurrent batches per shard, Lambda still ensures in\-order processing at the partition\-key level\. - -**Topics** -+ [Configuring your data stream and function](#services-kinesis-configure) -+ [Execution role permissions](#events-kinesis-permissions) -+ [Configuring a stream as an event source](#services-kinesis-eventsourcemapping) -+ [Event source mapping API](#services-kinesis-api) -+ [Error handling](#services-kinesis-errors) -+ [Amazon CloudWatch metrics](#events-kinesis-metrics) -+ [Tutorial: Using AWS Lambda with Amazon Kinesis](with-kinesis-example.md) -+ [Sample function code](with-kinesis-create-package.md) -+ [AWS SAM template for a Kinesis application](with-kinesis-example-use-app-spec.md) - -## Configuring your data stream and function - -Your Lambda function is a consumer application for your data stream\. It processes one batch of records at a time from each shard\. You can map a Lambda function to a data stream \(standard iterator\), or to a consumer of a stream \([enhanced fan\-out](https://docs.aws.amazon.com/kinesis/latest/dev/introduction-to-enhanced-consumers.html)\)\. - -For standard iterators, Lambda polls each shard in your Kinesis stream for records at a base rate of once per second\. When more records are available, Lambda keeps processing batches until the function catches up with the stream\. The event source mapping shares read throughput with other consumers of the shard\. - -To minimize latency and maximize read throughput, create a data stream consumer\. Stream consumers get a dedicated connection to each shard that doesn't impact other applications reading from the stream\. The dedicated throughput can help if you have many applications reading the same data, or if you're reprocessing a stream with large records\. - -Stream consumers use HTTP/2 to reduce latency by pushing records to Lambda over a long\-lived connection and by compressing request headers\. You can create a stream consumer with the Kinesis [RegisterStreamConsumer](https://docs.aws.amazon.com/kinesis/latest/APIReference/API_RegisterStreamConsumer.html) API\. - -``` -$ aws kinesis register-stream-consumer --consumer-name con1 \ ---stream-arn arn:aws:kinesis:us-east-2:123456789012:stream/lambda-stream -{ - "Consumer": { - "ConsumerName": "con1", - "ConsumerARN": "arn:aws:kinesis:us-east-2:123456789012:stream/lambda-stream/consumer/con1:1540591608", - "ConsumerStatus": "CREATING", - "ConsumerCreationTimestamp": 1540591608.0 - } -} -``` - -To increase the speed at which your function processes records, add shards to your data stream\. Lambda processes records in each shard in order\. It stops processing additional records in a shard if your function returns an error\. With more shards, there are more batches being processed at once, which lowers the impact of errors on concurrency\. - -If your function can't scale up to handle the total number of concurrent batches, [request a limit increase](gettingstarted-limits.md) or [reserve concurrency](configuration-concurrency.md) for your function\. - -## Execution role permissions - -Lambda needs the following permissions to manage resources that are related to your Kinesis data stream\. Add them to your function's [execution role](lambda-intro-execution-role.md)\. -+ [kinesis:DescribeStream](https://docs.aws.amazon.com/kinesis/latest/APIReference/API_DescribeStream.html) -+ [kinesis:DescribeStreamSummary](https://docs.aws.amazon.com/kinesis/latest/APIReference/API_DescribeStreamSummary.html) -+ [kinesis:GetRecords](https://docs.aws.amazon.com/kinesis/latest/APIReference/API_GetRecords.html) -+ [kinesis:GetShardIterator](https://docs.aws.amazon.com/kinesis/latest/APIReference/API_GetShardIterator.html) -+ [kinesis:ListShards](https://docs.aws.amazon.com/kinesis/latest/APIReference/API_ListShards.html) -+ [kinesis:ListStreams](https://docs.aws.amazon.com/kinesis/latest/APIReference/API_ListStreams.html) -+ [kinesis:SubscribeToShard](https://docs.aws.amazon.com/kinesis/latest/APIReference/API_SubscribeToShard.html) - -The `AWSLambdaKinesisExecutionRole` managed policy includes these permissions\. For more information, see [AWS Lambda execution role](lambda-intro-execution-role.md)\. - -To send records of failed batches to a queue or topic, your function needs additional permissions\. Each destination service requires a different permission, as follows: -+ **Amazon SQS** – [sqs:SendMessage](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SendMessage.html) -+ **Amazon SNS** – [sns:Publish](https://docs.aws.amazon.com/sns/latest/api/API_Publish.html) - -## Configuring a stream as an event source - -Create an event source mapping to tell Lambda to send records from your data stream to a Lambda function\. You can create multiple event source mappings to process the same data with multiple Lambda functions, or to process items from multiple data streams with a single function\. - -To configure your function to read from Kinesis in the Lambda console, create a **Kinesis** trigger\. - -**To create a trigger** - -1. Open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions)\. - -1. Choose a function\. - -1. Under **Designer**, choose **Add trigger**\. - -1. Choose a trigger type\. - -1. Configure the required options and then choose **Add**\. - -Lambda supports the following options for Kinesis event sources\. - -**Event source options** -+ **Kinesis stream** – The Kinesis stream to read records from\. -+ **Consumer** \(optional\) – Use a stream consumer to read from the stream over a dedicated connection\. -+ **Batch size** – The number of records to send to the function in each batch, up to 10,000\. Lambda passes all of the records in the batch to the function in a single call, as long as the total size of the events doesn't exceed the [payload limit](gettingstarted-limits.md) for synchronous invocation \(6 MB\)\. -+ **Batch window** – Specify the maximum amount of time to gather records before invoking the function, in seconds\. -+ **Starting position** – Process only new records, all existing records, or records created after a certain date\. - + **Latest** – Process new records that are added to the stream\. - + **Trim horizon** – Process all records in the stream\. - + **At timestamp** – Process records starting from a specific time\. - - After processing any existing records, the function is caught up and continues to process new records\. -+ **On\-failure destination** – An SQS queue or SNS topic for records that can't be processed\. When Lambda discards a batch of records because it's too old or has exhausted all retries, it sends details about the batch to the queue or topic\. -+ **Retry attempts** – The maximum number of times that Lambda retries when the function returns an error\. This doesn't apply to service errors or throttles where the batch didn't reach the function\. -+ **Maximum age of record** – The maximum age of a record that Lambda sends to your function\. -+ **Split batch on error** – When the function returns an error, split the batch into two before retrying\. -+ **Concurrent batches per shard** – Process multiple batches from the same shard concurrently\. -+ **Enabled** – Disable the event source to stop processing records\. Lambda keeps track of the last record processed and resumes processing from that point when it's reenabled\. - -To manage the event source configuration later, choose the trigger in the designer\. - -## Event source mapping API - -To manage event source mappings with the AWS CLI or AWS SDK, use the following API actions: -+ [CreateEventSourceMapping](API_CreateEventSourceMapping.md) -+ [ListEventSourceMappings](API_ListEventSourceMappings.md) -+ [GetEventSourceMapping](API_GetEventSourceMapping.md) -+ [UpdateEventSourceMapping](API_UpdateEventSourceMapping.md) -+ [DeleteEventSourceMapping](API_DeleteEventSourceMapping.md) - -To create the event source mapping with the AWS CLI, use the `create-event-source-mapping` command\. The following example uses the AWS CLI to map a function named `my-function` to a Kinesis data stream\. The data stream is specified by an Amazon Resource Name \(ARN\), with a batch size of 500, starting from the timestamp in Unix time\. - -``` -$ aws lambda create-event-source-mapping --function-name my-function \ ---batch-size 500 --starting-position AT_TIMESTAMP --starting-position-timestamp 1541139109 \ ---event-source-arn arn:aws:kinesis:us-east-2:123456789012:stream/lambda-stream -{ - "UUID": "2b733gdc-8ac3-cdf5-af3a-1827b3b11284", - "BatchSize": 500, - "MaximumBatchingWindowInSeconds": 0, - "ParallelizationFactor": 1, - "EventSourceArn": "arn:aws:kinesis:us-east-2:123456789012:stream/lambda-stream", - "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function", - "LastModified": 1541139209.351, - "LastProcessingResult": "No records processed", - "State": "Creating", - "StateTransitionReason": "User action", - "DestinationConfig": {}, - "MaximumRecordAgeInSeconds": 604800, - "BisectBatchOnFunctionError": false, - "MaximumRetryAttempts": 10000 -} -``` - -To use a consumer, specify the consumer's ARN instead of the stream's ARN\. - -Configure additional options to customize how batches are processed and to specify when to discard records that can't be processed\. The following example updates an event source mapping to send a failure record to an SQS queue after two retry attempts, or if the records are more than an hour old\. - -``` -$ aws lambda update-event-source-mapping --uuid f89f8514-cdd9-4602-9e1f-01a5b77d449b \ ---maximum-retry-attempts 2 --maximum-record-age-in-seconds 3600 ---destination-config '{"OnFailure": {"Destination": "arn:aws:sqs:us-east-2:123456789012:dlq"}}' -{ - "UUID": "f89f8514-cdd9-4602-9e1f-01a5b77d449b", - "BatchSize": 100, - "MaximumBatchingWindowInSeconds": 0, - "ParallelizationFactor": 1, - "EventSourceArn": "arn:aws:kinesis:us-east-2:123456789012:stream/lambda-stream", - "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function", - "LastModified": 1573243620.0, - "LastProcessingResult": "PROBLEM: Function call failed", - "State": "Updating", - "StateTransitionReason": "User action", - "DestinationConfig": {}, - "MaximumRecordAgeInSeconds": 604800, - "BisectBatchOnFunctionError": false, - "MaximumRetryAttempts": 10000 -} -``` - -Updated settings are applied asynchronously and aren't reflected in the output until the process completes\. Use the `get-event-source-mapping` command to view the current status\. - -``` -$ aws lambda get-event-source-mapping --uuid f89f8514-cdd9-4602-9e1f-01a5b77d449b -{ - "UUID": "f89f8514-cdd9-4602-9e1f-01a5b77d449b", - "BatchSize": 100, - "MaximumBatchingWindowInSeconds": 0, - "ParallelizationFactor": 1, - "EventSourceArn": "arn:aws:kinesis:us-east-2:123456789012:stream/lambda-stream", - "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function", - "LastModified": 1573244760.0, - "LastProcessingResult": "PROBLEM: Function call failed", - "State": "Enabled", - "StateTransitionReason": "User action", - "DestinationConfig": { - "OnFailure": { - "Destination": "arn:aws:sqs:us-east-2:123456789012:dlq" - } - }, - "MaximumRecordAgeInSeconds": 3600, - "BisectBatchOnFunctionError": false, - "MaximumRetryAttempts": 2 -} -``` - -To process multiple batches concurrently, use the `--parallelization-factor` option\. - -``` -$ aws lambda update-event-source-mapping --uuid 2b733gdc-8ac3-cdf5-af3a-1827b3b11284 \ ---parallelization-factor 5 -``` - -## Error handling - -The event source mapping that reads records from your Kinesis stream invokes your function synchronously and retries on errors\. If the function is throttled or the Lambda service returns an error without invoking the function, Lambda retries until the records expire or exceed the maximum age that you configure on the event source mapping\. - -If the function receives the records but returns an error, Lambda retries until the records in the batch expire, exceed the maximum age, or reach the configured retry limit\. For function errors, you can also configure the event source mapping to split a failed batch into two batches\. Retrying with smaller batches isolates bad records and works around timeout issues\. Splitting a batch does not count towards the retry limit\. - -If the error handling measures fail, Lambda discards the records and continues processing batches from the stream\. With the default settings, this means that a bad record can block processing on the affected shard for up to one week\. To avoid this, configure your function's event source mapping with a reasonable number of retries and a maximum record age that fits your use case\. - -To retain a record of discarded batches, configure a failed\-event destination\. Lambda sends a document to the destination queue or topic with details about the batch\. - -**To configure a destination for failed\-event records** - -1. Open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions)\. - -1. Choose a function\. - -1. Under **Designer**, choose **Add destination**\. - -1. For **Source**, choose **Stream invocation**\. - -1. For **Stream**, choose a stream that is mapped to the function\. - -1. For **Destination type**, choose the type of resource that receives the invocation record\. - -1. For **Destination**, choose a resource\. - -1. Choose **Save**\. - -The following example shows an invocation record for a Kinesis stream\. - -**Example Invocation Record** - -``` -{ - "requestContext": { - "requestId": "c9b8fa9f-5a7f-xmpl-af9c-0c604cde93a5", - "functionArn": "arn:aws:lambda:us-east-2:123456789012:function:myfunction", - "condition": "RetryAttemptsExhausted", - "approximateInvokeCount": 1 - }, - "responseContext": { - "statusCode": 200, - "executedVersion": "$LATEST", - "functionError": "Unhandled" - }, - "version": "1.0", - "timestamp": "2019-11-14T00:38:06.021Z", - "KinesisBatchInfo": { - "shardId": "shardId-000000000001", - "startSequenceNumber": "49601189658422359378836298521827638475320189012309704722", - "endSequenceNumber": "49601189658422359378836298522902373528957594348623495186", - "approximateArrivalOfFirstRecord": "2019-11-14T00:38:04.835Z", - "approximateArrivalOfLastRecord": "2019-11-14T00:38:05.580Z", - "batchSize": 500, - "streamArn": "arn:aws:kinesis:us-east-2:123456789012:stream/mystream" - } -} -``` - -You can use this information to retrieve the affected records from the stream for troubleshooting\. The actual records aren't included, so you must process this record and retrieve them from the stream before they expire and are lost\. - -## Amazon CloudWatch metrics - -Lambda emits the `IteratorAge` metric when your function finishes processing a batch of records\. The metric indicates how old the last record in the batch was when processing finished\. If your function is processing new events, you can use the iterator age to estimate the latency between when a record is added and when the function processes it\. - -An increasing trend in iterator age can indicate issues with your function\. For more information, see [Working with AWS Lambda function metrics](monitoring-metrics.md)\. \ No newline at end of file diff --git a/doc_source/with-on-demand-custom-android.md b/doc_source/with-on-demand-custom-android.md deleted file mode 100644 index b12d8432..00000000 --- a/doc_source/with-on-demand-custom-android.md +++ /dev/null @@ -1,11 +0,0 @@ -# Invoking Lambda functions with the AWS Mobile SDK for Android - -You can call a Lambda function from a mobile application\. Put business logic in functions to separate its development lifecycle from that of front\-end clients, making mobile applications less complex to develop and maintain\. With the Mobile SDK for Android, you [use Amazon Cognito to authenticate users and authorize requests](with-android-example.md)\. - -When you invoke a function from a mobile application, you choose the event structure, [invocation type](lambda-invocation.md), and permission model\. You can use [aliases](configuration-aliases.md) to enable seamless updates to your function code, but otherwise the function and application are tightly coupled\. As you add more functions, you can create an API layer to decouple your function code from your front\-end clients and improve performance\. - -To create a fully\-featured web API for your mobile and web applications, use Amazon API Gateway\. With API Gateway, you can add custom authorizers, throttle requests, and cache results for all of your functions\. For more information, see [Using AWS Lambda with Amazon API Gateway](services-apigateway.md)\. - -**Topics** -+ [Tutorial: Using AWS Lambda with the Mobile SDK for Android](with-android-example.md) -+ [Sample function code](with-android-create-package.md) \ No newline at end of file diff --git a/doc_source/with-s3-example-deployment-pkg.md b/doc_source/with-s3-example-deployment-pkg.md deleted file mode 100644 index b191c637..00000000 --- a/doc_source/with-s3-example-deployment-pkg.md +++ /dev/null @@ -1,351 +0,0 @@ -# Sample Amazon S3 function code - -Sample code is available for the following languages\. - -**Topics** -+ [Node\.js 12\.x](#with-s3-example-deployment-pkg-nodejs) -+ [Java 11](#with-s3-example-deployment-pkg-java) -+ [Python 3](#with-s3-example-deployment-pkg-python) - -## Node\.js 12\.x - -The following example code receives an Amazon S3 event input and processes the message that it contains\. It resizes an image in the source bucket and saves the output to the target bucket\. - -**Example index\.js** - -``` -// dependencies -const AWS = require('aws-sdk'); -const util = require('util'); -const sharp = require('sharp'); - -// get reference to S3 client -const s3 = new AWS.S3(); - -exports.handler = async (event, context, callback) => { - - // Read options from the event parameter. - console.log("Reading options from event:\n", util.inspect(event, {depth: 5})); - const srcBucket = event.Records[0].s3.bucket.name; - // Object key may have spaces or unicode non-ASCII characters. - const srcKey = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, " ")); - const dstBucket = srcBucket + "-resized"; - const dstKey = "resized-" + srcKey; - - // Infer the image type from the file suffix. - const typeMatch = srcKey.match(/\.([^.]*)$/); - if (!typeMatch) { - console.log("Could not determine the image type."); - return; - } - - // Check that the image type is supported - const imageType = typeMatch[1].toLowerCase(); - if (imageType != "jpg" && imageType != "png") { - console.log(`Unsupported image type: ${imageType}`); - return; - } - - // Download the image from the S3 source bucket. - - try { - const params = { - Bucket: srcBucket, - Key: srcKey - }; - var origimage = await s3.getObject(params).promise(); - - } catch (error) { - console.log(error); - return; - } - - // set thumbnail width. Resize will set the height automatically to maintain aspect ratio. - const width = 200; - - // Use the Sharp module to resize the image and save in a buffer. - try { - var buffer = await sharp(origimage.Body).resize(width).toBuffer(); - - } catch (error) { - console.log(error); - return; - } - - // Upload the thumbnail image to the destination bucket - try { - const destparams = { - Bucket: dstBucket, - Key: dstKey, - Body: buffer, - ContentType: "image" - }; - - const putResult = await s3.putObject(destparams).promise(); - - } catch (error) { - console.log(error); - return; - } - - console.log('Successfully resized ' + srcBucket + '/' + srcKey + - ' and uploaded to ' + dstBucket + '/' + dstKey); -}; -``` - -The deployment package is a \.zip file containing your Lambda function code and dependencies\. - -**To create a deployment package** - -1. Create a folder \(`examplefolder`\), and then create a subfolder \(`node_modules`\)\. - -1. Install dependencies\. The code examples use the following libraries: - + AWS SDK for JavaScript in Node\.js - + Sharp for node\.js - - The AWS Lambda runtime already has the AWS SDK for JavaScript in Node\.js, so you only need to install the Sharp library\. Open a command prompt, navigate to the `examplefolder`, and install the libraries using the `npm` command, which is part of Node\.js\. For Linux, use the following command\. - - ``` - $ npm install sharp - ``` - - For macOS, use the following command\. - - ``` - $ npm install --arch=x64 --platform=linux --target=12.13.0 sharp - ``` - -1. Save the sample code to a file named index\.js\. - -1. Review the preceding code and note the following: - + The function knows the source bucket name and the key name of the object from the event data it receives as parameters\. If the object is a \.jpg, the code creates a thumbnail and saves it to the target bucket\. - + The code assumes that the destination bucket exists and its name is a concatenation of the source bucket name followed by the string `-resized`\. For example, if the source bucket identified in the event data is `examplebucket`, the code assumes you have an `examplebucket-resized` destination bucket\. - + For the thumbnail it creates, the code derives its key name as the concatenation of the string `resized-` followed by the source object key name\. For example, if the source object key is `sample.jpg`, the code creates a thumbnail object that has the key `resized-sample.jpg`\. - -1. Save the file as `index.js` in `examplefolder`\. After you complete this step, you will have the following folder structure: - - ``` - index.js - /node_modules/sharp - ``` - -1. Zip the index\.js file and the node\_modules folder as `CreateThumbnail.zip`\. - -## Java 11 - -The following is example Java code that reads incoming Amazon S3 events and creates a thumbnail\. Note that it implements the `RequestHandler` interface provided in the `aws-lambda-java-core` library\. Therefore, at the time you create a Lambda function you specify the class as the handler \(that is, `example.handler`\)\. For more information about using interfaces to provide a handler, see [Handler interfaces](java-handler.md#java-handler-interfaces)\. - -The `S3Event` type that the handler uses as the input type is one of the predefined classes in the `aws-lambda-java-events`  library that provides methods for you to easily read information from the incoming Amazon S3 event\. The handler returns a string as output\. - -**Example Handler\.java** - -``` -package example; - -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.awt.image.BufferedImage; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.imageio.ImageIO; - -import com.amazonaws.AmazonServiceException; -import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; -import com.amazonaws.services.lambda.runtime.events.S3Event; -import com.amazonaws.services.s3.AmazonS3; -import com.amazonaws.services.s3.event.S3EventNotification.S3EventNotificationRecord; -import com.amazonaws.services.s3.model.GetObjectRequest; -import com.amazonaws.services.s3.model.ObjectMetadata; -import com.amazonaws.services.s3.model.S3Object; -import com.amazonaws.services.s3.AmazonS3ClientBuilder; - -public class Handler implements - RequestHandler { - private static final float MAX_WIDTH = 100; - private static final float MAX_HEIGHT = 100; - private final String JPG_TYPE = (String) "jpg"; - private final String JPG_MIME = (String) "image/jpeg"; - private final String PNG_TYPE = (String) "png"; - private final String PNG_MIME = (String) "image/png"; - - public String handleRequest(S3Event s3event, Context context) { - try { - S3EventNotificationRecord record = s3event.getRecords().get(0); - - String srcBucket = record.getS3().getBucket().getName(); - - // Object key may have spaces or unicode non-ASCII characters. - String srcKey = record.getS3().getObject().getUrlDecodedKey(); - - String dstBucket = srcBucket + "-resized"; - String dstKey = "resized-" + srcKey; - - // Sanity check: validate that source and destination are different - // buckets. - if (srcBucket.equals(dstBucket)) { - System.out - .println("Destination bucket must not match source bucket."); - return ""; - } - - // Infer the image type. - Matcher matcher = Pattern.compile(".*\\.([^\\.]*)").matcher(srcKey); - if (!matcher.matches()) { - System.out.println("Unable to infer image type for key " - + srcKey); - return ""; - } - String imageType = matcher.group(1); - if (!(JPG_TYPE.equals(imageType)) && !(PNG_TYPE.equals(imageType))) { - System.out.println("Skipping non-image " + srcKey); - return ""; - } - - // Download the image from S3 into a stream - AmazonS3 s3Client = AmazonS3ClientBuilder.defaultClient(); - S3Object s3Object = s3Client.getObject(new GetObjectRequest( - srcBucket, srcKey)); - InputStream objectData = s3Object.getObjectContent(); - - // Read the source image - BufferedImage srcImage = ImageIO.read(objectData); - int srcHeight = srcImage.getHeight(); - int srcWidth = srcImage.getWidth(); - // Infer the scaling factor to avoid stretching the image - // unnaturally - float scalingFactor = Math.min(MAX_WIDTH / srcWidth, MAX_HEIGHT - / srcHeight); - int width = (int) (scalingFactor * srcWidth); - int height = (int) (scalingFactor * srcHeight); - - BufferedImage resizedImage = new BufferedImage(width, height, - BufferedImage.TYPE_INT_RGB); - Graphics2D g = resizedImage.createGraphics(); - // Fill with white before applying semi-transparent (alpha) images - g.setPaint(Color.white); - g.fillRect(0, 0, width, height); - // Simple bilinear resize - g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, - RenderingHints.VALUE_INTERPOLATION_BILINEAR); - g.drawImage(srcImage, 0, 0, width, height, null); - g.dispose(); - - // Re-encode image to target format - ByteArrayOutputStream os = new ByteArrayOutputStream(); - ImageIO.write(resizedImage, imageType, os); - InputStream is = new ByteArrayInputStream(os.toByteArray()); - // Set Content-Length and Content-Type - ObjectMetadata meta = new ObjectMetadata(); - meta.setContentLength(os.size()); - if (JPG_TYPE.equals(imageType)) { - meta.setContentType(JPG_MIME); - } - if (PNG_TYPE.equals(imageType)) { - meta.setContentType(PNG_MIME); - } - - // Uploading to S3 destination bucket - System.out.println("Writing to: " + dstBucket + "/" + dstKey); - try { - s3Client.putObject(dstBucket, dstKey, is, meta); - } - catch(AmazonServiceException e) - { - System.err.println(e.getErrorMessage()); - System.exit(1); - } - System.out.println("Successfully resized " + srcBucket + "/" - + srcKey + " and uploaded to " + dstBucket + "/" + dstKey); - return "Ok"; - } catch (IOException e) { - throw new RuntimeException(e); - } - } -} -``` - -Amazon S3 invokes your Lambda function using the `Event` invocation type, where AWS Lambda executes the code asynchronously\. What you return does not matter\. However, in this case we are implementing an interface that requires us to specify a return type, so in this example the handler uses `String` as the return type\. - -**Dependencies** -+ `aws-lambda-java-core` -+ `aws-lambda-java-events` -+ `aws-java-sdk` - -Build the code with the Lambda library dependencies to create a deployment package\. For instructions, see [AWS Lambda deployment package in Java](java-package.md)\. - -## Python 3 - -The following example code receives an Amazon S3 event input and processes the message that it contains\. It resizes an image in the source bucket and saves the output to the target bucket\. - -**Example lambda\_function\.py** - -``` -import boto3 -import os -import sys -import uuid -from urllib.parse import unquote_plus -from PIL import Image -import PIL.Image - -s3_client = boto3.client('s3') - -def resize_image(image_path, resized_path): - with Image.open(image_path) as image: - image.thumbnail(tuple(x / 2 for x in image.size)) - image.save(resized_path) - -def lambda_handler(event, context): - for record in event['Records']: - bucket = record['s3']['bucket']['name'] - key = unquote_plus(record['s3']['object']['key']) - tmpkey = key.replace('/', '') - download_path = '/tmp/{}{}'.format(uuid.uuid4(), tmpkey) - upload_path = '/tmp/resized-{}'.format(tmpkey) - s3_client.download_file(bucket, key, download_path) - resize_image(download_path, upload_path) - s3_client.upload_file(upload_path, '{}-resized'.format(bucket), key) -``` - -**Note** -The image library used by this code must be installed in a Linux environment in order to create a working deployment package\. - -**To create a deployment package** - -1. Copy the sample code into a file named `lambda_function.py`\. - -1. Create a virtual environment\. - - ``` - s3-python$ virtualenv v-env - s3-python$ source v-env/bin/activate - ``` - -1. Install libraries in the virtual environment - - ``` - (v-env) s3-python$ pip install Pillow boto3 - ``` - -1. Create a deployment package with the contents of the installed libraries\. - - ``` - (v-env) s3-python$ cd $VIRTUAL_ENV/lib/python3.8/site-packages - (v-env) python-s3/v-env/lib/python3.8/site-packages$ zip -r9 ${OLDPWD}/function.zip . - ``` - -1. Add the handler code to the deployment package and deactivate the virtual environment\. - - ``` - (v-env) python-s3/v-env/lib/python3.8/site-packages$ cd ${OLDPWD} - (v-env) python-s3$ zip -g function.zip lambda_function.py - adding: lambda_function.py (deflated 55%) - (v-env) python-s3$ deactivate - ``` \ No newline at end of file diff --git a/doc_source/with-s3-example-use-app-spec.md b/doc_source/with-s3-example-use-app-spec.md deleted file mode 100644 index 156cac9b..00000000 --- a/doc_source/with-s3-example-use-app-spec.md +++ /dev/null @@ -1,31 +0,0 @@ -# AWS SAM template for an Amazon S3 application - -You can build this application using [AWS SAM](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/)\. To learn more about creating AWS SAM templates, see [ AWS SAM template basics](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-template-basics.html) in the *AWS Serverless Application Model Developer Guide*\. - -Below is a sample AWS SAM template for the Lambda application from the [tutorial](with-s3-example.md)\. Copy the text below to a \.yaml file and save it next to the ZIP package you created previously\. Note that the `Handler` and `Runtime` parameter values should match the ones you used when you created the function in the previous section\. - -**Example template\.yaml** - -``` -AWSTemplateFormatVersion: '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Resources: - CreateThumbnail: - Type: AWS::Serverless::Function - Properties: - Handler: handler - Runtime: runtime - Timeout: 60 - Policies: AWSLambdaExecute - Events: - CreateThumbnailEvent: - Type: S3 - Properties: - Bucket: !Ref SrcBucket - Events: s3:ObjectCreated:* - - SrcBucket: - Type: AWS::S3::Bucket -``` - -For information on how to package and deploy your serverless application using the package and deploy commands, see [Deploying serverless applications](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-deploying.html) in the *AWS Serverless Application Model Developer Guide*\. \ No newline at end of file diff --git a/doc_source/with-s3-example.md b/doc_source/with-s3-example.md deleted file mode 100644 index 04506db6..00000000 --- a/doc_source/with-s3-example.md +++ /dev/null @@ -1,325 +0,0 @@ -# Tutorial: Using AWS Lambda with Amazon S3 - -Suppose you want to create a thumbnail for each image file that is uploaded to a bucket\. You can create a Lambda function \(`CreateThumbnail`\) that Amazon S3 can invoke when objects are created\. Then, the Lambda function can read the image object from the source bucket and create a thumbnail image target bucket\. - -Upon completing this tutorial, you will have the following Amazon S3, Lambda, and IAM resources in your account: - -![\[Image NOT FOUND\]](http://docs.aws.amazon.com/lambda/latest/dg/images/s3-admin-iser-walkthrough-10.png) - -**Lambda resources** -+ A Lambda function\. -+ An access policy associated with your Lambda function that grants Amazon S3 permission to invoke the Lambda function\. - -**IAM resources** -+ An execution role that grants permissions that your Lambda function needs through the permissions policy associated with this role\. - -**Amazon S3 resources** -+ A source bucket with a notification configuration that invokes the Lambda function\. -+ A target bucket where the function saves resized images\. - -## Prerequisites - -This tutorial assumes that you have some knowledge of basic Lambda operations and the Lambda console\. If you haven't already, follow the instructions in [Getting started with AWS Lambda](getting-started.md) to create your first Lambda function\. - -To follow the procedures in this guide, you will need a command line terminal or shell to run commands\. Commands are shown in listings preceded by a prompt symbol \($\) and the name of the current directory, when appropriate: - -``` -~/lambda-project$ this is a command -this is output -``` - -For long commands, an escape character \(`\`\) is used to split a command over multiple lines\. - -On Linux and macOS, use your preferred shell and package manager\. On Windows 10, you can [install the Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows\-integrated version of Ubuntu and Bash\. - -Install npm to manage the function's dependencies\. - -The tutorial uses AWS CLI commands to create and invoke the Lambda function\. Install the [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html) and [configure it with your AWS credentials](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html) - -## Create the execution role - -Create the [execution role](lambda-intro-execution-role.md) that gives your function permission to access AWS resources\. - -**To create an execution role** - -1. Open the [roles page](https://console.aws.amazon.com/iam/home#/roles) in the IAM console\. - -1. Choose **Create role**\. - -1. Create a role with the following properties\. - + **Trusted entity** – **AWS Lambda**\. - + **Permissions** – **AWSLambdaExecute**\. - + **Role name** – **lambda\-s3\-role**\. - -The **AWSLambdaExecute** policy has the permissions that the function needs to manage objects in Amazon S3 and write logs to CloudWatch Logs\. - -## Create buckets and upload a sample object - -Follow the steps to create buckets and upload an object\. - -1. Open the [Amazon S3 console](https://console.aws.amazon.com/s3)\. - -1. Create two buckets\. The target bucket name must be *source* followed by **\-resized**, where *source* is the name of the bucket you want to use for the source\. For example, `mybucket` and `mybucket-resized`\. - -1. In the source bucket, upload a \.jpg object, `HappyFace.jpg`\. - - When you invoke the Lambda function manually before you connect to Amazon S3, you pass sample event data to the function that specifies the source bucket and `HappyFace.jpg` as the newly created object so you need to create this sample object first\. - -## Create the function - -The following example code receives an Amazon S3 event input and processes the message that it contains\. It resizes an image in the source bucket and saves the output to the target bucket\. - -**Note** -For sample code in other languages, see [Sample Amazon S3 function code](with-s3-example-deployment-pkg.md)\. - -**Example index\.js** - -``` -// dependencies -const AWS = require('aws-sdk'); -const util = require('util'); -const sharp = require('sharp'); - -// get reference to S3 client -const s3 = new AWS.S3(); - -exports.handler = async (event, context, callback) => { - - // Read options from the event parameter. - console.log("Reading options from event:\n", util.inspect(event, {depth: 5})); - const srcBucket = event.Records[0].s3.bucket.name; - // Object key may have spaces or unicode non-ASCII characters. - const srcKey = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, " ")); - const dstBucket = srcBucket + "-resized"; - const dstKey = "resized-" + srcKey; - - // Infer the image type from the file suffix. - const typeMatch = srcKey.match(/\.([^.]*)$/); - if (!typeMatch) { - console.log("Could not determine the image type."); - return; - } - - // Check that the image type is supported - const imageType = typeMatch[1].toLowerCase(); - if (imageType != "jpg" && imageType != "png") { - console.log(`Unsupported image type: ${imageType}`); - return; - } - - // Download the image from the S3 source bucket. - - try { - const params = { - Bucket: srcBucket, - Key: srcKey - }; - var origimage = await s3.getObject(params).promise(); - - } catch (error) { - console.log(error); - return; - } - - // set thumbnail width. Resize will set the height automatically to maintain aspect ratio. - const width = 200; - - // Use the Sharp module to resize the image and save in a buffer. - try { - var buffer = await sharp(origimage.Body).resize(width).toBuffer(); - - } catch (error) { - console.log(error); - return; - } - - // Upload the thumbnail image to the destination bucket - try { - const destparams = { - Bucket: dstBucket, - Key: dstKey, - Body: buffer, - ContentType: "image" - }; - - const putResult = await s3.putObject(destparams).promise(); - - } catch (error) { - console.log(error); - return; - } - - console.log('Successfully resized ' + srcBucket + '/' + srcKey + - ' and uploaded to ' + dstBucket + '/' + dstKey); -}; -``` - -Review the preceding code and note the following: -+ The function knows the source bucket name and the key name of the object from the event data it receives as parameters\. If the object is a \.jpg or a \.png, the code creates a thumbnail and saves it to the target bucket\. -+ The code assumes that the destination bucket exists and its name is a concatenation of the source bucket name followed by the string `-resized`\. For example, if the source bucket identified in the event data is `examplebucket`, the code assumes you have an `examplebucket-resized` destination bucket\. -+ For the thumbnail it creates, the code derives its key name as the concatenation of the string `resized-` followed by the source object key name\. For example, if the source object key is `sample.jpg`, the code creates a thumbnail object that has the key `resized-sample.jpg`\. - -The deployment package is a \.zip file containing your Lambda function code and dependencies\. - -**To create a deployment package** - -1. Save the function code as `index.js` in a folder named `lambda-s3`\. - -1. Install the Sharp library with npm\. For Linux, use the following command\. - - ``` - lambda-s3$ npm install sharp - ``` - - For macOS, use the following command\. - - ``` - lambda-s3$ npm install --arch=x64 --platform=linux --target=12.13.0 sharp - ``` - - After you complete this step, you will have the following folder structure: - - ``` - lambda-s3 - |- index.js - |- /node_modules/sharp - └ /node_modules/... - ``` - -1. Create a deployment package with the function code and dependencies\. - - ``` - lambda-s3$ zip -r function.zip . - ``` - -**To create the function** -+ Create a Lambda function with the `create-function` command\. - - ``` - $ aws lambda create-function --function-name CreateThumbnail \ - --zip-file fileb://function.zip --handler index.handler --runtime nodejs12.x \ - --timeout 10 --memory-size 1024 \ - --role arn:aws:iam::123456789012:role/lambda-s3-role - ``` - -For the role parameter, replace the number sequence with your AWS account ID\. The preceding example command specifies a 10\-second timeout value as the function configuration\. Depending on the size of objects you upload, you might need to increase the timeout value using the following AWS CLI command\. - -``` -$ aws lambda update-function-configuration --function-name CreateThumbnail --timeout 30 -``` - -## Test the Lambda function - -In this step, you invoke the Lambda function manually using sample Amazon S3 event data\. - -**To test the Lambda function** - -1. Save the following Amazon S3 sample event data in a file and save it as `inputFile.txt`\. You need to update the JSON by providing your *sourcebucket* name and a \.jpg object key\. - - ``` - { - "Records":[ - { - "eventVersion":"2.0", - "eventSource":"aws:s3", - "awsRegion":"us-west-2", - "eventTime":"1970-01-01T00:00:00.000Z", - "eventName":"ObjectCreated:Put", - "userIdentity":{ - "principalId":"AIDAJDPLRKLG7UEXAMPLE" - }, - "requestParameters":{ - "sourceIPAddress":"127.0.0.1" - }, - "responseElements":{ - "x-amz-request-id":"C3D13FE58DE4C810", - "x-amz-id-2":"FMyUVURIY8/IgAtTv8xRjskZQpcIZ9KG4V5Wp6S7S/JRWeUWerMUE5JgHvANOjpD" - }, - "s3":{ - "s3SchemaVersion":"1.0", - "configurationId":"testConfigRule", - "bucket":{ - "name":"sourcebucket", - "ownerIdentity":{ - "principalId":"A3NL1KOZZKExample" - }, - "arn":"arn:aws:s3:::sourcebucket" - }, - "object":{ - "key":"HappyFace.jpg", - "size":1024, - "eTag":"d41d8cd98f00b204e9800998ecf8427e", - "versionId":"096fKKXTRTtl3on89fVO.nfljtsv6qko" - } - } - } - ] - } - ``` - -1. Run the following Lambda CLI `invoke` command to invoke the function\. Note that the command requests asynchronous execution\. You can optionally invoke it synchronously by specifying `RequestResponse` as the `invocation-type` parameter value\. - - ``` - $ aws lambda invoke --function-name CreateThumbnail --invocation-type Event \ - --payload file://inputFile.txt outputfile.txt - ``` - -1. Verify that the thumbnail was created in the target bucket\. - -## Configure Amazon S3 to publish events - -In this step, you add the remaining configuration so that Amazon S3 can publish object\-created events to AWS Lambda and invoke your Lambda function\. You do the following in this step: -+ Add permissions to the Lambda function access policy to allow Amazon S3 to invoke the function\. -+ Add notification configuration to your source bucket\. In the notification configuration, you provide the following: - + Event type for which you want Amazon S3 to publish events\. For this tutorial, you specify the `s3:ObjectCreated:*` event type so that Amazon S3 publishes events when objects are created\. - + Lambda function to invoke\. - -**To add permissions to the function policy** - -1. Run the following Lambda CLI `add-permission` command to grant Amazon S3 service principal \(`s3.amazonaws.com`\) permissions to perform the `lambda:InvokeFunction` action\. Note that permission is granted to Amazon S3 to invoke the function only if the following conditions are met: - + An object\-created event is detected on a specific bucket\. - + The bucket is owned by your account\. If you delete a bucket, it is possible for another account to create a bucket with the same ARN\. - - ``` - $ aws lambda add-permission --function-name CreateThumbnail --principal s3.amazonaws.com \ - --statement-id s3invoke --action "lambda:InvokeFunction" \ - --source-arn arn:aws:s3:::sourcebucket \ - --source-account account-id - ``` - -1. Verify the function's access policy by running the AWS CLI `get-policy` command\. - - ``` - $ aws lambda get-policy --function-name CreateThumbnail - ``` - -Add notification configuration on the source bucket to request Amazon S3 to publish object\-created events to Lambda\. - -**Important** -This procedure configures the bucket to invoke your function every time an object is created in it\. Ensure that you configure this option only on the source bucket and do not create objects in the source bucket from the function that is triggered\. Otherwise, your function could cause itself to be [invoked continuously in a loop](with-s3.md#services-s3-runaway)\. - -**To configure notifications** - -1. Open the [Amazon S3 console](https://console.aws.amazon.com/s3)\. - -1. Choose the source bucket\. - -1. Choose **Properties**\. - -1. Under **Events**, configure a notification with the following settings\. - + **Name** – **lambda\-trigger**\. - + **Events** – **ObjectCreate \(All\)**\. - + **Send to** – **Lambda function**\. - + **Lambda** – **CreateThumbnail**\. - -For more information on event configuration, see [Enabling event notifications](https://docs.aws.amazon.com/AmazonS3/latest/user-guide/enable-event-notifications.html) in the *Amazon Simple Storage Service Console User Guide*\. - -## Test the setup - -Now you can test the setup as follows: - -1. Upload \.jpg or \.png objects to the source bucket using the Amazon S3 console\. - -1. Verify that the thumbnail was created in the target bucket using the `CreateThumbnail` function\. - -1. View logs in the CloudWatch console\. \ No newline at end of file diff --git a/doc_source/with-s3.md b/doc_source/with-s3.md deleted file mode 100644 index 55ba6ea4..00000000 --- a/doc_source/with-s3.md +++ /dev/null @@ -1,60 +0,0 @@ -# Using AWS Lambda with Amazon S3 events - -You can use Lambda to process [event notifications](https://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html) from Amazon Simple Storage Service\. Amazon S3 can send an event to a Lambda function when an object is created or deleted\. You configure notification settings on a bucket, and grant Amazon S3 permission to invoke a function on the function's resource\-based permissions policy\. - -**Warning** -If your Lambda function uses the same bucket that triggers it, it could cause the function to execute in a loop\. For example, if the bucket triggers a function each time an object is uploaded, and the function uploads an object to the bucket, then the function indirectly triggers itself\. To avoid this, use two buckets, or configure the trigger to only apply to a prefix used for incoming objects\. - -Amazon S3 invokes your function [asynchronously](invocation-async.md) with an event that contains details about the object\. The following example shows an event that Amazon S3 sent when a deployment package was uploaded to Amazon S3\. - -**Example Amazon S3 notification event** - -``` -{ - "Records": [ - { - "eventVersion": "2.1", - "eventSource": "aws:s3", - "awsRegion": "us-east-2", - "eventTime": "2019-09-03T19:37:27.192Z", - "eventName": "ObjectCreated:Put", - "userIdentity": { - "principalId": "AWS:AIDAINPONIXQXHT3IKHL2" - }, - "requestParameters": { - "sourceIPAddress": "205.255.255.255" - }, - "responseElements": { - "x-amz-request-id": "D82B88E5F771F645", - "x-amz-id-2": "vlR7PnpV2Ce81l0PRw6jlUpck7Jo5ZsQjryTjKlc5aLWGVHPZLj5NeC6qMa0emYBDXOo6QBU0Wo=" - }, - "s3": { - "s3SchemaVersion": "1.0", - "configurationId": "828aa6fc-f7b5-4305-8584-487c791949c1", - "bucket": { - "name": "lambda-artifacts-deafc19498e3f2df", - "ownerIdentity": { - "principalId": "A3I5XTEXAMAI3E" - }, - "arn": "arn:aws:s3:::lambda-artifacts-deafc19498e3f2df" - }, - "object": { - "key": "b21b84d653bb07b05b1e6b33684dc11b", - "size": 1305107, - "eTag": "b21b84d653bb07b05b1e6b33684dc11b", - "sequencer": "0C0F6F405D6ED209E1" - } - } - } - ] -} -``` - -To invoke your function, Amazon S3 needs permission from the function's [resource\-based policy](access-control-resource-based.md)\. When you configure an Amazon S3 trigger in the Lambda console, the console modifies the resource\-based policy to allow Amazon S3 to invoke the function if the bucket name and account ID match\. If you configure the notification in Amazon S3, you use the Lambda API to update the policy\. You can also use the Lambda API to grant permission to another account, or restrict permission to a designated alias\. - -If your function uses the AWS SDK to manage Amazon S3 resources, it also needs Amazon S3 permissions in its [execution role](lambda-intro-execution-role.md)\. - -**Topics** -+ [Tutorial: Using AWS Lambda with Amazon S3](with-s3-example.md) -+ [Sample Amazon S3 function code](with-s3-example-deployment-pkg.md) -+ [AWS SAM template for an Amazon S3 application](with-s3-example-use-app-spec.md) \ No newline at end of file diff --git a/doc_source/with-scheduledevents-example-use-app-spec.md b/doc_source/with-scheduledevents-example-use-app-spec.md deleted file mode 100644 index 045efa89..00000000 --- a/doc_source/with-scheduledevents-example-use-app-spec.md +++ /dev/null @@ -1,52 +0,0 @@ -# AWS SAM template for a CloudWatch Events application - -You can build this application using [AWS SAM](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/)\. To learn more about creating AWS SAM templates, see [ AWS SAM template basics](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-template-basics.html) in the *AWS Serverless Application Model Developer Guide*\. - -Below is a sample AWS SAM template for the Lambda application from the [tutorial](services-cloudwatchevents-tutorial.md)\. Copy the text below to a \.yaml file and save it next to the ZIP package you created previously\. Note that the `Handler` and `Runtime` parameter values should match the ones you used when you created the function in the previous section\. - -**Example template\.yaml** - -``` -AWSTemplateFormatVersion: '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Parameters: - NotificationEmail: - Type: String -Resources: - CheckWebsitePeriodically: - Type: AWS::Serverless::Function - Properties: - Handler: LambdaFunctionOverHttps.handler - Runtime: runtime - Policies: AmazonDynamoDBFullAccess - Events: - CheckWebsiteScheduledEvent: - Type: Schedule - Properties: - Schedule: rate(1 minute) - - AlarmTopic: - Type: AWS::SNS::Topic - Properties: - Subscription: - - Protocol: email - Endpoint: !Ref NotificationEmail - - Alarm: - Type: AWS::CloudWatch::Alarm - Properties: - AlarmActions: - - !Ref AlarmTopic - ComparisonOperator: GreaterThanOrEqualToThreshold - Dimensions: - - Name: FunctionName - Value: !Ref CheckWebsitePeriodically - EvaluationPeriods: 1 - MetricName: Errors - Namespace: AWS/Lambda - Period: 60 - Statistic: Sum - Threshold: '1' -``` - -For information on how to package and deploy your serverless application using the package and deploy commands, see [Deploying serverless applications](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-deploying.html) in the *AWS Serverless Application Model Developer Guide*\. \ No newline at end of file diff --git a/doc_source/with-sns-create-package.md b/doc_source/with-sns-create-package.md deleted file mode 100644 index 8bfd510a..00000000 --- a/doc_source/with-sns-create-package.md +++ /dev/null @@ -1,114 +0,0 @@ -# Sample function code - -Sample code is available for the following languages\. - -**Topics** -+ [Node\.js 8](#with-sns-example-deployment-pkg-nodejs) -+ [Java 11](#with-sns-example-deployment-pkg-java) -+ [Go](#with-sns-example-deployment-pkg-go) -+ [Python 3](#with-sns-example-deployment-pkg-python) - -## Node\.js 8 - -The following example processes messages from Amazon SNS, and logs their contents\. - -**Example index\.js** - -``` -console.log('Loading function'); - -exports.handler = function(event, context, callback) { -// console.log('Received event:', JSON.stringify(event, null, 4)); - - var message = event.Records[0].Sns.Message; - console.log('Message received from SNS:', message); - callback(null, "Success"); -}; -``` - -Zip up the sample code to create a deployment package\. For instructions, see [AWS Lambda deployment package in Node\.js](nodejs-package.md)\. - -## Java 11 - -The following example processes messages from Amazon SNS, and logs their contents\. - -**Example LambdaWithSNS\.java** - -``` -package example; - -import java.text.SimpleDateFormat; -import java.util.Calendar; - -import com.amazonaws.services.lambda.runtime.RequestHandler; -import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.events.SNSEvent; - -public class LogEvent implements RequestHandler { - public Object handleRequest(SNSEvent request, Context context){ - String timeStamp = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss").format(Calendar.getInstance().getTime()); - context.getLogger().log("Invocation started: " + timeStamp); - context.getLogger().log(request.getRecords().get(0).getSNS().getMessage()); - - timeStamp = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss").format(Calendar.getInstance().getTime()); - context.getLogger().log("Invocation completed: " + timeStamp); - return null; - } -} -``` - -**Dependencies** -+ `aws-lambda-java-core` -+ `aws-lambda-java-events` - -Build the code with the Lambda library dependencies to create a deployment package\. For instructions, see [AWS Lambda deployment package in Java](java-package.md)\. - -## Go - -The following example processes messages from Amazon SNS, and logs their contents\. - -**Example lambda\_handler\.go** - -``` -package main - -import ( - "context" - "fmt" - "github.com/aws/aws-lambda-go/lambda" - "github.com/aws/aws-lambda-go/events" -) - -func handler(ctx context.Context, snsEvent events.SNSEvent) { - for _, record := range snsEvent.Records { - snsRecord := record.SNS - fmt.Printf("[%s %s] Message = %s \n", record.EventSource, snsRecord.Timestamp, snsRecord.Message) - } -} - -func main() { - lambda.Start(handler) -} -``` - -Build the executable with `go build` and create a deployment package\. For instructions, see [AWS Lambda deployment package in Go](golang-package.md)\. - -## Python 3 - -The following example processes messages from Amazon SNS, and logs their contents\. - -**Example lambda\_handler\.py** - -``` -from __future__ import print_function -import json -print('Loading function') - -def lambda_handler(event, context): - #print("Received event: " + json.dumps(event, indent=2)) - message = event['Records'][0]['Sns']['Message'] - print("From SNS: " + message) - return message -``` - -Zip up the sample code to create a deployment package\. For instructions, see [AWS Lambda deployment package in Python](python-package.md)\. \ No newline at end of file diff --git a/doc_source/with-sns-example.md b/doc_source/with-sns-example.md deleted file mode 100644 index ffd55c3e..00000000 --- a/doc_source/with-sns-example.md +++ /dev/null @@ -1,143 +0,0 @@ -# Tutorial: Using AWS Lambda with Amazon Simple Notification Service - -You can use a Lambda function in one AWS account to subscribe to an Amazon SNS topic in a separate AWS account\. In this tutorial, you use the AWS Command Line Interface to perform AWS Lambda operations such as creating a Lambda function, creating an Amazon SNS topic and granting permissions to allow these two resources to access each other\. - -## Prerequisites - -This tutorial assumes that you have some knowledge of basic Lambda operations and the Lambda console\. If you haven't already, follow the instructions in [Getting started with AWS Lambda](getting-started.md) to create your first Lambda function\. - -To follow the procedures in this guide, you will need a command line terminal or shell to run commands\. Commands are shown in listings preceded by a prompt symbol \($\) and the name of the current directory, when appropriate: - -``` -~/lambda-project$ this is a command -this is output -``` - -For long commands, an escape character \(`\`\) is used to split a command over multiple lines\. - -On Linux and macOS, use your preferred shell and package manager\. On Windows 10, you can [install the Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows\-integrated version of Ubuntu and Bash\. - -In the tutorial, you use two accounts\. The AWS CLI commands illustrate this by using two [named profiles](https://docs.aws.amazon.com/cli/latest/userguide/cli-multiple-profiles.html), each configured for use with a different account\. If you use profiles with different names, or the default profile and one named profile, modify the commands as needed\. - -## Create an Amazon SNS topic - -From account A, create the source Amazon SNS topic\. - -``` -$ aws sns create-topic --name lambda-x-account --profile accountA -``` - -Note the topic ARN that is returned by the command\. You will need it when you add permissions to the Lambda function to subscribe to the topic\. - -## Create the execution role - -From account B, create the [execution role](lambda-intro-execution-role.md) that gives your function permission to access AWS resources\. - -**To create an execution role** - -1. Open the [roles page](https://console.aws.amazon.com/iam/home#/roles) in the IAM console\. - -1. Choose **Create role**\. - -1. Create a role with the following properties\. - + **Trusted entity** – **AWS Lambda**\. - + **Permissions** – **AWSLambdaBasicExecutionRole**\. - + **Role name** – **lambda\-sns\-role**\. - -The **AWSLambdaBasicExecutionRole** policy has the permissions that the function needs to write logs to CloudWatch Logs\. - -## Create a Lambda function - -From account B, create the function that processes events from Amazon SNS\. The following example code receives an Amazon SNS event input and processes the messages that it contains\. For illustration, the code writes some of the incoming event data to CloudWatch Logs\. - -**Note** -For sample code in other languages, see [Sample function code](with-sns-create-package.md)\. - -**Example index\.js** - -``` -console.log('Loading function'); - -exports.handler = function(event, context, callback) { -// console.log('Received event:', JSON.stringify(event, null, 4)); - - var message = event.Records[0].Sns.Message; - console.log('Message received from SNS:', message); - callback(null, "Success"); -}; -``` - -**To create the function** - -1. Copy the sample code into a file named `index.js`\. - -1. Create a deployment package\. - - ``` - $ zip function.zip index.js - ``` - -1. Create a Lambda function with the `create-function` command\. - - ``` - $ aws lambda create-function --function-name SNS-X-Account \ - --zip-file fileb://function.zip --handler index.handler --runtime nodejs12.x \ - --role arn:aws:iam::01234567891B:role/service-role/lambda-sns-execution-role \ - --timeout 60 --profile accountB - ``` - -Note the function ARN that is returned by the command\. You will need it when you add permissions to allow Amazon SNS to invoke your function\. - -## Set up cross\-account permissions - -From account A, grant permission to account B to subscribe to the topic: - -``` -$ aws sns add-permission --label lambda-access --aws-account-id 12345678901B \ ---topic-arn arn:aws:sns:us-east-2:12345678901A:lambda-x-account \ ---action-name Subscribe ListSubscriptionsByTopic Receive --profile accountA -``` - -From account B, add the Lambda permission to allow invocation from Amazon SNS\. - -``` -$ aws lambda add-permission --function-name SNS-X-Account \ ---source-arn arn:aws:sns:us-east-2:12345678901A:lambda-x-account \ ---statement-id sns-x-account --action "lambda:InvokeFunction" \ ---principal sns.amazonaws.com --profile accountB -{ - "Statement": "{\"Condition\":{\"ArnLike\":{\"AWS:SourceArn\":\"arn:aws:lambda:us-east-2:12345678901B:function:SNS-X-Account\"}},\"Action\":[\"lambda:InvokeFunction\"],\"Resource\":\"arn:aws:lambda:us-east-2:01234567891A:function:SNS-X-Account\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"sns.amazonaws.com\"},\"Sid\":\"sns-x-account1\"}" -} -``` - -Do not use the `--source-account` parameter to add a source account to the Lambda policy when adding the policy\. Source account is not supported for Amazon SNS event sources and will result in access being denied\. - -## Create a subscription - -From account B, subscribe the Lambda function to the topic\. When a message is sent to the `lambda-x-account` topic in account A, Amazon SNS invokes the `SNS-X-Account` function in account B\. - -``` -$ aws sns subscribe --protocol lambda \ ---topic-arn arn:aws:sns:us-east-2:12345678901A:lambda-x-account \ ---notification-endpoint arn:aws:lambda:us-east-2:12345678901B:function:SNS-X-Account \ ---profile accountB -{ - "SubscriptionArn": "arn:aws:sns:us-east-2:12345678901A:lambda-x-account:5d906xxxx-7c8x-45dx-a9dx-0484e31c98xx" -} -``` - -The output contains the ARN of the topic subscription\. - -## Test subscription - -From account A, test the subscription\. Type `Hello World` into a text file and save it as `message.txt`\. Then run the following command: - -``` -$ aws sns publish --message file://message.txt --subject Test \ ---topic-arn arn:aws:sns:us-east-2:12345678901A:lambda-x-account \ ---profile accountA -``` - -This will return a message id with a unique identifier, indicating the message has been accepted by the Amazon SNS service\. Amazon SNS will then attempt to deliver it to the topic's subscribers\. Alternatively, you could supply a JSON string directly to the `message` parameter, but using a text file allows for line breaks in the message\. - -To learn more about Amazon SNS, see [What is Amazon Simple Notification Service](https://docs.aws.amazon.com/sns/latest/dg/)\. \ No newline at end of file diff --git a/doc_source/with-sns.md b/doc_source/with-sns.md deleted file mode 100644 index fea17f30..00000000 --- a/doc_source/with-sns.md +++ /dev/null @@ -1,51 +0,0 @@ -# Using AWS Lambda with Amazon SNS - -You can use a Lambda function to process Amazon Simple Notification Service notifications\. Amazon SNS supports Lambda functions as a target for messages sent to a topic\. You can subscribe your function to topics in the same account or in other AWS accounts\. - -Amazon SNS invokes your function [asynchronously](invocation-async.md) with an event that contains a message and metadata\. - -**Example Amazon SNS message event** - -``` -{ - "Records": [ - { - "EventVersion": "1.0", - "EventSubscriptionArn": "arn:aws:sns:us-east-2:123456789012:sns-lambda:21be56ed-a058-49f5-8c98-aedd2564c486", - "EventSource": "aws:sns", - "Sns": { - "SignatureVersion": "1", - "Timestamp": "2019-01-02T12:45:07.000Z", - "Signature": "tcc6faL2yUC6dgZdmrwh1Y4cGa/ebXEkAi6RibDsvpi+tE/1+82j...65r==", - "SigningCertUrl": "https://sns.us-east-2.amazonaws.com/SimpleNotificationService-ac565b8b1a6c5d002d285f9598aa1d9b.pem", - "MessageId": "95df01b4-ee98-5cb9-9903-4c221d41eb5e", - "Message": "Hello from SNS!", - "MessageAttributes": { - "Test": { - "Type": "String", - "Value": "TestString" - }, - "TestBinary": { - "Type": "Binary", - "Value": "TestBinary" - } - }, - "Type": "Notification", - "UnsubscribeUrl": "https://sns.us-east-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-east-2:123456789012:test-lambda:21be56ed-a058-49f5-8c98-aedd2564c486", - "TopicArn":"arn:aws:sns:us-east-2:123456789012:sns-lambda", - "Subject": "TestInvoke" - } - } - ] -} -``` - -For asynchronous invocation, Lambda queues the message and handles retries\. If Amazon SNS is unable to reach Lambda or the message is rejected, Amazon SNS retries at increasing intervals over several hours\. For details, see [Reliability](https://aws.amazon.com/sns/faqs/#Reliability) in the Amazon SNS FAQ\. - -In order to perform cross account Amazon SNS deliveries to Lambda, you need to authorize your Lambda function to be invoked from Amazon SNS\. In turn, Amazon SNS needs to allow the Lambda account to subscribe to the Amazon SNS topic\. For example, if the Amazon SNS topic is in account A and the Lambda function is in account B, both accounts must grant permissions to the other to access their respective resources\. Since not all the options for setting up cross\-account permissions are available from the AWS console, you use the AWS CLI to set up the entire process\. - -For more information, see [Invoking Lambda functions using Amazon SNS notifications](https://docs.aws.amazon.com/sns/latest/dg/sns-lambda.html) in the *Amazon Simple Notification Service Developer Guide*\. - -**Topics** -+ [Tutorial: Using AWS Lambda with Amazon Simple Notification Service](with-sns-example.md) -+ [Sample function code](with-sns-create-package.md) \ No newline at end of file diff --git a/doc_source/with-sqs-create-package.md b/doc_source/with-sqs-create-package.md deleted file mode 100644 index e99ab0a1..00000000 --- a/doc_source/with-sqs-create-package.md +++ /dev/null @@ -1,165 +0,0 @@ -# Sample Amazon SQS function code - -Sample code is available for the following languages\. - -**Topics** -+ [Node\.js](#with-sqs-example-deployment-pkg-nodejs) -+ [Java](#with-sqs-example-deployment-pkg-java) -+ [C\#](#with-sqs-example-deployment-pkg-dotnet) -+ [Go](#with-sqs-example-deployment-pkg-go) -+ [Python](#with-sqs-example-deployment-pkg-python) - -## Node\.js - -The following is example code that receives an Amazon SQS event message as input and processes it\. For illustration, the code writes some of the incoming event data to CloudWatch Logs\. - -**Example index\.js \(Node\.js 8\)** - -``` -exports.handler = async function(event, context) { - event.Records.forEach(record => { - const { body } = record; - console.log(body); - }); - return {}; -} -``` - -**Example index\.js \(Node\.js 6\)** - -``` -event.Records.forEach(function(record) { - var body = record.body; - console.log(body); - }); - callback(null, "message"); -}; -``` - -Zip up the sample code to create a deployment package\. For instructions, see [AWS Lambda deployment package in Node\.js](nodejs-package.md)\. - -## Java - -The following is example Java code that receives an Amazon SQS event message as input and processes it\. For illustration, the code writes some of the incoming event data to CloudWatch Logs\. - -In the code, `handleRequest` is the handler\. The handler uses the predefined `SQSEvent` class that is defined in the `aws-lambda-java-events` library\. - -**Example Handler\.java** - -``` -package example; - -import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; -import com.amazonaws.services.lambda.runtime.events.SQSEvent; -import com.amazonaws.services.lambda.runtime.events.SQSEvent.SQSMessage; - -public class Handler implements RequestHandler{ - @Override - public Void handleRequest(SQSEvent event, Context context) - { - for(SQSMessage msg : event.getRecords()){ - System.out.println(new String(msg.getBody())); - } - return null; - } -} -``` - -**Dependencies** -+ `aws-lambda-java-core` -+ `aws-lambda-java-events` - -Build the code with the Lambda library dependencies to create a deployment package\. For instructions, see [AWS Lambda deployment package in Java](java-package.md)\. - -## C\# - -The following is example C\# code that receives an Amazon SQS event message as input and processes it\. For illustration, the code writes some of the incoming event data to the console\. - - In the code, `handleRequest` is the handler\. The handler uses the predefined `SQSEvent` class that is defined in the `AWS.Lambda.SQSEvents` library\. - -**Example ProcessingSQSRecords\.cs** - -``` -[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] - -namespace SQSLambdaFunction -{ - public class SQSLambdaFunction - { - public string HandleSQSEvent(SQSEvent sqsEvent, ILambdaContext context) - { - Console.WriteLine($"Beginning to process {sqsEvent.Records.Count} records..."); - - foreach (var record in sqsEvent.Records) - { - Console.WriteLine($"Message ID: {record.MessageId}"); - Console.WriteLine($"Event Source: {record.EventSource}"); - - Console.WriteLine($"Record Body:"); - Console.WriteLine(record.Body); - } - - Console.WriteLine("Processing complete."); - - return $"Processed {sqsEvent.Records.Count} records."; - } - } -} -``` - -Replace the `Program.cs` in a \.NET Core project with the above sample\. For instructions, see [AWS Lambda Deployment Package in C\#](csharp-package.md)\. - -## Go - -The following is example Go code that receives an Amazon SQS event message as input and processes it\. For illustration, the code writes some of the incoming event data to CloudWatch Logs\. - - In the code, `handler` is the handler\. The handler uses the predefined `SQSEvent` class that is defined in the `aws-lambda-go-events` library\. - -**Example ProcessSQSRecords\.go** - -``` -package main - -import ( - "context" - "fmt" - - "github.com/aws/aws-lambda-go/events" - "github.com/aws/aws-lambda-go/lambda" -) - -func handler(ctx context.Context, sqsEvent events.SQSEvent) error { - for _, message := range sqsEvent.Records { - fmt.Printf("The message %s for event source %s = %s \n", message.MessageId, message.EventSource, message.Body) - } - - return nil -} - -func main() { - lambda.Start(handler) -} -``` - -Build the executable with `go build` and create a deployment package\. For instructions, see [AWS Lambda deployment package in Go](golang-package.md)\. - -## Python - -The following is example Python code that accepts an Amazon SQS record as input and processes it\. For illustration, the code writes to some of the incoming event data to CloudWatch Logs\. - -Follow the instructions to create a AWS Lambda function deployment package\. - -**Example ProcessSQSRecords\.py** - -``` -from __future__ import print_function - -def lambda_handler(event, context): - for record in event['Records']: - print ("test") - payload=record["body"] - print(str(payload)) -``` - -Zip up the sample code to create a deployment package\. For instructions, see [AWS Lambda deployment package in Python](python-package.md)\. \ No newline at end of file diff --git a/doc_source/with-sqs-example-use-app-spec.md b/doc_source/with-sqs-example-use-app-spec.md deleted file mode 100644 index f187c610..00000000 --- a/doc_source/with-sqs-example-use-app-spec.md +++ /dev/null @@ -1,29 +0,0 @@ -# AWS SAM template for an Amazon SQS application - -You can build this application using [AWS SAM](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/)\. To learn more about creating AWS SAM templates, see [ AWS SAM template basics](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-template-basics.html) in the *AWS Serverless Application Model Developer Guide*\. - -Below is a sample AWS SAM template for the Lambda application from the [tutorial](with-sqs-example.md)\. Copy the text below to a \.yaml file and save it next to the ZIP package you created previously\. Note that the `Handler` and `Runtime` parameter values should match the ones you used when you created the function in the previous section\. - -**Example template\.yaml** - -``` -AWSTemplateFormatVersion: '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Description: Example of processing messages on an SQS queue with Lambda -Resources: - MySQSQueueFunction: - Type: AWS::Serverless::Function - Properties: - Handler: index.handler - Runtime: nodejs12.x - Events: - MySQSEvent: - Type: SQS - Properties: - Queue: !GetAtt MySqsQueue.Arn - BatchSize: 10 - MySqsQueue: - Type: AWS::SQS::Queue -``` - -For information on how to package and deploy your serverless application using the package and deploy commands, see [Deploying serverless applications](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-deploying.html) in the *AWS Serverless Application Model Developer Guide*\. \ No newline at end of file diff --git a/doc_source/with-sqs-example.md b/doc_source/with-sqs-example.md deleted file mode 100644 index dadd2f76..00000000 --- a/doc_source/with-sqs-example.md +++ /dev/null @@ -1,156 +0,0 @@ -# Tutorial: Using AWS Lambda with Amazon Simple Queue Service - -In this tutorial, you create a Lambda function to consume messages from an [Amazon SQS](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/Welcome.html) queue\. - -## Prerequisites - -This tutorial assumes that you have some knowledge of basic Lambda operations and the Lambda console\. If you haven't already, follow the instructions in [Getting started with AWS Lambda](getting-started.md) to create your first Lambda function\. - -To follow the procedures in this guide, you will need a command line terminal or shell to run commands\. Commands are shown in listings preceded by a prompt symbol \($\) and the name of the current directory, when appropriate: - -``` -~/lambda-project$ this is a command -this is output -``` - -For long commands, an escape character \(`\`\) is used to split a command over multiple lines\. - -On Linux and macOS, use your preferred shell and package manager\. On Windows 10, you can [install the Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows\-integrated version of Ubuntu and Bash\. - -## Create the execution role - -Create the [execution role](lambda-intro-execution-role.md) that gives your function permission to access AWS resources\. - -**To create an execution role** - -1. Open the [roles page](https://console.aws.amazon.com/iam/home#/roles) in the IAM console\. - -1. Choose **Create role**\. - -1. Create a role with the following properties\. - + **Trusted entity** – **AWS Lambda**\. - + **Permissions** – **AWSLambdaSQSQueueExecutionRole**\. - + **Role name** – **lambda\-sqs\-role**\. - -The **AWSLambdaSQSQueueExecutionRole** policy has the permissions that the function needs to read items from Amazon SQS and write logs to CloudWatch Logs\. - -## Create the function - -The following example code receives an Amazon SQS event input and processes the messages that it contains\. For illustration, the code writes some of the incoming event data to CloudWatch Logs\. - -**Note** -For sample code in other languages, see [Sample Amazon SQS function code](with-sqs-create-package.md)\. - -**Example index\.js** - -``` -exports.handler = async function(event, context) { - event.Records.forEach(record => { - const { body } = record; - console.log(body); - }); - return {}; -} -``` - -**To create the function** - -1. Copy the sample code into a file named `index.js`\. - -1. Create a deployment package\. - - ``` - $ zip function.zip index.js - ``` - -1. Create a Lambda function with the `create-function` command\. - - ``` - $ aws lambda create-function --function-name ProcessSQSRecord \ - --zip-file fileb://function.zip --handler index.handler --runtime nodejs12.x \ - --role arn:aws:iam::123456789012:role/lambda-sqs-role - ``` - -## Test the function - -Invoke your Lambda function manually using the `invoke` AWS Lambda CLI command and a sample Amazon Simple Queue Service event\. - -If the handler returns normally without exceptions, Lambda considers the message processed successfully and begins reading new messages in the queue\. Once a message is processed successfully, it is automatically deleted from the queue\. If the handler throws an exception, Lambda considers the input of messages as not processed and invokes the function with the same batch of messages\. - -1. Copy the following JSON into a file and save it as `input.txt`\. - - ``` - { - "Records": [ - { - "messageId": "059f36b4-87a3-44ab-83d2-661975830a7d", - "receiptHandle": "AQEBwJnKyrHigUMZj6rYigCgxlaS3SLy0a...", - "body": "test", - "attributes": { - "ApproximateReceiveCount": "1", - "SentTimestamp": "1545082649183", - "SenderId": "AIDAIENQZJOLO23YVJ4VO", - "ApproximateFirstReceiveTimestamp": "1545082649185" - }, - "messageAttributes": {}, - "md5OfBody": "098f6bcd4621d373cade4e832627b4f6", - "eventSource": "aws:sqs", - "eventSourceARN": "arn:aws:sqs:us-east-2:123456789012:my-queue", - "awsRegion": "us-east-2" - } - ] - } - ``` - -1. Execute the following `invoke` command\. - - ``` - $ aws lambda invoke --function-name ProcessSQSRecord \ - --payload file://input.txt outputfile.txt - ``` - -1. Verify the output in the `outputfile.txt` file\. - -## Create an Amazon SQS queue - -Create an Amazon SQS queue that the Lambda function can use as an event source\. - -**To create a queue** - -1. Sign in to the AWS Management Console and open the Amazon SQS console at [https://console\.aws\.amazon\.com/sqs/](https://console.aws.amazon.com/sqs/)\. - -1. In the Amazon SQS console, create a queue\. - -1. Write down or otherwise record the identifying queue ARN \(Amazon Resource Name\)\. You need this in the next step when you associate the queue with your Lambda function\. - -Create an event source mapping in AWS Lambda\. This event source mapping associates the Amazon SQS queue with your Lambda function\. After you create this event source mapping, AWS Lambda starts polling the queue\. - -Test the end\-to\-end experience\. As you perform queue updates, Amazon Simple Queue Service writes messages to the queue\. AWS Lambda polls the queue, detects new records and executes your Lambda function on your behalf by passing events, in this case Amazon SQS messages, to the function\. - -## Configure the event source - -To create a mapping between the specified Amazon SQS queue and the Lambda function, run the following AWS CLI `create-event-source-mapping` command\. After the command executes, write down or otherwise record the UUID\. You'll need this UUID to refer to the event source mapping in any other commands, for example, if you choose to delete the event source mapping\. - -``` -$ aws lambda create-event-source-mapping --function-name ProcessSQSRecord --batch-size 10 \ ---event-source-arn arn:aws:sqs:us-east-2:123456789012:my-queue -``` - -You can get the list of event source mappings by running the following command\. - -``` -$ aws lambda list-event-source-mappings --function-name ProcessSQSRecord \ ---event-source-arn arn:aws:sqs:us-east-2:123456789012:my-queue -``` - -The list returns all of the event source mappings you created, and for each mapping it shows the `LastProcessingResult`, among other things\. This field is used to provide an informative message if there are any problems\. Values such as `No records processed` \(indicates that AWS Lambda has not started polling or that there are no records in the queue\) and `OK` \(indicates AWS Lambda successfully read records from the queue and invoked your Lambda function\) indicate that there no issues\. If there are issues, you receive an error message\. - -## Test the setup - -Now you can test the setup as follows: - -1. In the Amazon SQS console, send messages to the queue\. Amazon SQS writes records of these actions to the queue\. - -1. AWS Lambda polls the queue and when it detects updates, it invokes your Lambda function by passing in the event data it finds in the queue\. - -1. Your function executes and creates logs in Amazon CloudWatch\. You can verify the logs reported in the Amazon CloudWatch console\. \ No newline at end of file diff --git a/doc_source/with-sqs.md b/doc_source/with-sqs.md deleted file mode 100644 index aea99361..00000000 --- a/doc_source/with-sqs.md +++ /dev/null @@ -1,162 +0,0 @@ -# Using AWS Lambda with Amazon SQS - -You can use an AWS Lambda function to process messages in an Amazon Simple Queue Service \(Amazon SQS\) queue\. Lambda [event source mappings](invocation-eventsourcemapping.md) support [standard queues](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/standard-queues.html) and [first\-in, first\-out \(FIFO\) queues](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/fifo-queues.html)\. With Amazon SQS, you can offload tasks from one component of your application by sending them to a queue and processing them asynchronously\. - -Lambda polls the queue and invokes your function [synchronously](invocation-sync.md) with an event that contains queue messages\. Lambda reads messages in batches and invokes your function once for each batch\. When your function successfully processes a batch, Lambda deletes its messages from the queue\. The following example shows an event for a batch of two messages\. - -**Example Amazon SQS message event \(standard queue\)** - -``` -{ - "Records": [ - { - "messageId": "059f36b4-87a3-44ab-83d2-661975830a7d", - "receiptHandle": "AQEBwJnKyrHigUMZj6rYigCgxlaS3SLy0a...", - "body": "Test message.", - "attributes": { - "ApproximateReceiveCount": "1", - "SentTimestamp": "1545082649183", - "SenderId": "AIDAIENQZJOLO23YVJ4VO", - "ApproximateFirstReceiveTimestamp": "1545082649185" - }, - "messageAttributes": {}, - "md5OfBody": "e4e68fb7bd0e697a0ae8f1bb342846b3", - "eventSource": "aws:sqs", - "eventSourceARN": "arn:aws:sqs:us-east-2:123456789012:my-queue", - "awsRegion": "us-east-2" - }, - { - "messageId": "2e1424d4-f796-459a-8184-9c92662be6da", - "receiptHandle": "AQEBzWwaftRI0KuVm4tP+/7q1rGgNqicHq...", - "body": "Test message.", - "attributes": { - "ApproximateReceiveCount": "1", - "SentTimestamp": "1545082650636", - "SenderId": "AIDAIENQZJOLO23YVJ4VO", - "ApproximateFirstReceiveTimestamp": "1545082650649" - }, - "messageAttributes": {}, - "md5OfBody": "e4e68fb7bd0e697a0ae8f1bb342846b3", - "eventSource": "aws:sqs", - "eventSourceARN": "arn:aws:sqs:us-east-2:123456789012:my-queue", - "awsRegion": "us-east-2" - } - ] -} -``` - -For FIFO queues, records contain additional attributes that are related to deduplication and sequencing\. - -**Example Amazon SQS message event \(FIFO queue\)** - -``` -{ - "Records": [ - { - "messageId": "11d6ee51-4cc7-4302-9e22-7cd8afdaadf5", - "receiptHandle": "AQEBBX8nesZEXmkhsmZeyIE8iQAMig7qw...", - "body": "Test message.", - "attributes": { - "ApproximateReceiveCount": "1", - "SentTimestamp": "1573251510774", - "SequenceNumber": "18849496460467696128", - "MessageGroupId": "1", - "SenderId": "AIDAIO23YVJENQZJOL4VO", - "MessageDeduplicationId": "1", - "ApproximateFirstReceiveTimestamp": "1573251510774" - }, - "messageAttributes": {}, - "md5OfBody": "e4e68fb7bd0e697a0ae8f1bb342846b3", - "eventSource": "aws:sqs", - "eventSourceARN": "arn:aws:sqs:us-east-2:123456789012:fifo.fifo", - "awsRegion": "us-east-2" - } - ] -} -``` - -When Lambda reads a batch, the messages stay in the queue but become hidden for the length of the queue's [visibility timeout](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html)\. If your function successfully processes the batch, Lambda deletes the messages from the queue\. If your function is [throttled](invocation-scaling.md), returns an error, or doesn't respond, the message becomes visible again\. All messages in a failed batch return to the queue, so your function code must be able to process the same message multiple times without side effects\. - -## Scaling and processing - -For standard queues, Lambda uses [long polling](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-long-polling.html) to poll a queue until it becomes active\. When messages are available, Lambda reads up to 5 batches and sends them to your function\. If messages are still available, Lambda increases the number of processes that are reading batches by up to 60 more instances per minute\. The maximum number of batches that can be processed simultaneously by an event source mapping is 1000\. - -For FIFO queues, Lambda sends messages to your function in the order that it receives them\. When you send a message to a FIFO queue, you specify a [message group ID](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/using-messagegroupid-property.html)\. Amazon SQS ensures that messages in the same group are delivered to Lambda in order\. Lambda sorts the messages into groups and sends only one batch at a time for a group\. If the function returns an error, all retries are attempted on the affected messages before Lambda receives additional messages from the same group\. - -Your function can scale in concurrency to the number of active message groups\. For more information, see [SQS FIFO as an event source](https://aws.amazon.com/blogs/compute/new-for-aws-lambda-sqs-fifo-as-an-event-source/) on the AWS Compute Blog\. - -## Configuring a queue for use with Lambda - -[Create an SQS queue](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/) to serve as an event source for your Lambda function\. Then configure the queue to allow time for your Lambda function to process each batch of events—and for Lambda to retry in response to throttling errors as it scales up\. - -To allow your function time to process each batch of records, set the source queue's visibility timeout to at least 6 times the [timeout](configuration-console.md) that you configure on your function\. The extra time allows for Lambda to retry if your function execution is throttled while your function is processing a previous batch\. - -If a message fails to be processed multiple times, Amazon SQS can send it to a [dead\-letter queue](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html)\. When your function returns an error, Lambda leaves it in the queue\. After the visibility timeout occurs, Lambda receives the message again\. To send messages to a second queue after a number of receives, configure a dead\-letter queue on your source queue\. - -**Note** -Make sure that you configure the dead\-letter queue on the source queue, not on the Lambda function\. The dead\-letter queue that you configure on a function is used for the function's [asynchronous invocation queue](invocation-async.md), not for event source queues\. - -If your function returns an error, or can't be invoked because it's at maximum concurrency, processing might succeed with additional attempts\. To give messages a better chance to be processed before sending them to the dead\-letter queue, set the `maxReceiveCount` on the source queue's redrive policy to at least **5**\. - -## Execution role permissions - -Lambda needs the following permissions to manage messages in your Amazon SQS queue\. Add them to your function's execution role\. -+ [sqs:ReceiveMessage](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_ReceiveMessage.html) -+ [sqs:DeleteMessage](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_DeleteMessage.html) -+ [sqs:GetQueueAttributes](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_GetQueueAttributes.html) - -For more information, see [AWS Lambda execution role](lambda-intro-execution-role.md)\. - -## Configuring a queue as an event source - -Create an event source mapping to tell Lambda to send items from your queue to a Lambda function\. You can create multiple event source mappings to process items from multiple queues with a single function\. When Lambda invokes the target function, the event can contain multiple items, up to a configurable maximum *batch size*\. - -To configure your function to read from Amazon SQS in the Lambda console, create an **SQS** trigger\. - -**To create a trigger** - -1. Open the Lambda console [Functions page](https://console.aws.amazon.com/lambda/home#/functions)\. - -1. Choose a function\. - -1. Under **Designer**, choose **Add trigger**\. - -1. Choose a trigger type\. - -1. Configure the required options and then choose **Add**\. - -Lambda supports the following options for Amazon SQS event sources\. - -**Event source options** -+ **SQS queue** – The Amazon SQS queue to read records from\. -+ **Batch size** – The number of items to read from the queue in each batch, up to 10\. The event might contain fewer items if the batch that Lambda read from the queue had fewer items\. -+ **Enabled** – Disable the event source to stop processing items\. - -To manage the event source configuration later, choose the trigger in the designer\. - -Configure your function timeout to allow enough time to process an entire batch of items\. If items take a long time to process, choose a smaller batch size\. A large batch size can improve efficiency for workloads that are very fast or have a lot of overhead\. However, if your function returns an error, all items in the batch return to the queue\. If you configure [reserved concurrency](configuration-concurrency.md) on your function, set a minimum of 5 concurrent executions to reduce the chance of throttling errors when Lambda invokes your function\. - -## Event source mapping APIs - -To manage event source mappings with the AWS CLI or AWS SDK, use the following API actions: -+ [CreateEventSourceMapping](API_CreateEventSourceMapping.md) -+ [ListEventSourceMappings](API_ListEventSourceMappings.md) -+ [GetEventSourceMapping](API_GetEventSourceMapping.md) -+ [UpdateEventSourceMapping](API_UpdateEventSourceMapping.md) -+ [DeleteEventSourceMapping](API_DeleteEventSourceMapping.md) - -The following example uses the AWS CLI to map a function named `my-function` to an Amazon SQS queue that is specified by its Amazon Resource Name \(ARN\), with a batch size of 5\. - -``` -$ aws lambda create-event-source-mapping --function-name my-function --batch-size 5 \ ---event-source-arn arn:aws:sqs:us-east-2:123456789012:my-queue -{ - "UUID": "2b733gdc-8ac3-cdf5-af3a-1827b3b11284", - "BatchSize": 5, - "EventSourceArn": "arn:aws:sqs:us-east-2:123456789012:my-queue", - "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function", - "LastModified": 1541139209.351, - "State": "Creating", - "StateTransitionReason": "USER_INITIATED" -} -``` \ No newline at end of file diff --git a/sample-apps/.gitignore b/sample-apps/.gitignore index 6599623c..61f810ce 100644 --- a/sample-apps/.gitignore +++ b/sample-apps/.gitignore @@ -11,8 +11,8 @@ build *.zip bin obj -main Gemfile.lock lib __pycache__ *.pyc +.DS_Store diff --git a/sample-apps/.vscode/settings.json b/sample-apps/.vscode/settings.json new file mode 100644 index 00000000..a6b86d56 --- /dev/null +++ b/sample-apps/.vscode/settings.json @@ -0,0 +1,4 @@ +{ + "java.configuration.updateBuildConfiguration": "automatic", + "java.jdt.ls.vmargs": "-XX:+UseParallelGC -XX:GCTimeRatio=4 -XX:AdaptiveSizePolicyWeight=90 -Dsun.zip.disableMemoryMapping=true -Xmx2G -Xms100m -Xlog:disable" +} \ No newline at end of file diff --git a/sample-apps/blank-csharp-with-layer/1-create-bucket-and-role.sh b/sample-apps/blank-csharp-with-layer/1-create-bucket-and-role.sh new file mode 100755 index 00000000..4b8676ae --- /dev/null +++ b/sample-apps/blank-csharp-with-layer/1-create-bucket-and-role.sh @@ -0,0 +1,12 @@ +#!/bin/bash +BUCKET_ID=$(dd if=/dev/random bs=8 count=1 2>/dev/null | od -An -tx1 | tr -d ' \t\n') +BUCKET_NAME=lambda-artifacts-$BUCKET_ID +LAYER_BUCKET_NAME=$BUCKET_NAME-dotnet-layer +echo $BUCKET_NAME > bucket-name.txt +aws s3 mb s3://$BUCKET_NAME +aws s3 mb s3://$LAYER_BUCKET_NAME + +aws iam create-role --role-name blank-csharp-role --assume-role-policy-document fileb://assume-policy.json +aws iam attach-role-policy --role-name blank-csharp-role --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole +aws iam attach-role-policy --role-name blank-csharp-role --policy-arn arn:aws:iam::aws:policy/AWSLambda_ReadOnlyAccess +aws iam attach-role-policy --role-name blank-csharp-role --policy-arn arn:aws:iam::aws:policy/AWSXrayWriteOnlyAccess diff --git a/sample-apps/blank-csharp-with-layer/2-build-layer.sh b/sample-apps/blank-csharp-with-layer/2-build-layer.sh new file mode 100755 index 00000000..67d491d8 --- /dev/null +++ b/sample-apps/blank-csharp-with-layer/2-build-layer.sh @@ -0,0 +1,6 @@ +#!/bin/bash +LAYER_BUCKET_NAME=$(cat bucket-name.txt)-dotnet-layer +cd src/blank-csharp +LAYER_ARN=$(dotnet lambda publish-layer blank-csharp-layer --layer-type runtime-package-store --s3-bucket "$LAYER_BUCKET_NAME" | tail -1 | cut -c 23-) +cd ../.. +echo $LAYER_ARN > layer-arn.txt diff --git a/sample-apps/blank-csharp-with-layer/3-deploy.sh b/sample-apps/blank-csharp-with-layer/3-deploy.sh new file mode 100755 index 00000000..1aa3bc45 --- /dev/null +++ b/sample-apps/blank-csharp-with-layer/3-deploy.sh @@ -0,0 +1,7 @@ +#!/bin/bash +set -eo pipefail +ARTIFACT_BUCKET=$(cat bucket-name.txt) +LAYER_ARN=$(cat layer-arn.txt) +cd src/blank-csharp +dotnet lambda deploy-function blank-csharp --function-layers $LAYER_ARN +cd ../../ diff --git a/sample-apps/blank-csharp-with-layer/4-invoke.sh b/sample-apps/blank-csharp-with-layer/4-invoke.sh new file mode 100755 index 00000000..877992ac --- /dev/null +++ b/sample-apps/blank-csharp-with-layer/4-invoke.sh @@ -0,0 +1,9 @@ +#!/bin/bash +set -eo pipefail +if [[ $(aws --version) =~ "aws-cli/2." ]]; then PAYLOAD_PROTOCOL="fileb"; else PAYLOAD_PROTOCOL="file"; fi; +while true; do + aws lambda invoke --function-name blank-csharp --payload $PAYLOAD_PROTOCOL://event.json out.json + cat out.json + echo "" + sleep 2 +done diff --git a/sample-apps/blank-csharp-with-layer/5-cleanup.sh b/sample-apps/blank-csharp-with-layer/5-cleanup.sh new file mode 100755 index 00000000..f76e1068 --- /dev/null +++ b/sample-apps/blank-csharp-with-layer/5-cleanup.sh @@ -0,0 +1,50 @@ +#!/bin/bash +set -eo pipefail +echo "Deleting function blank-csharp" +aws iam detach-role-policy --role-name blank-csharp-role --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole +aws iam detach-role-policy --role-name blank-csharp-role --policy-arn arn:aws:iam::aws:policy/AWSLambda_ReadOnlyAccess +aws iam detach-role-policy --role-name blank-csharp-role --policy-arn arn:aws:iam::aws:policy/AWSXrayWriteOnlyAccess +aws iam delete-role --role-name blank-csharp-role +aws lambda delete-function --function-name blank-csharp + +if [ -f bucket-name.txt ]; then + ARTIFACT_BUCKET=$(cat bucket-name.txt) + if [[ ! $ARTIFACT_BUCKET =~ lambda-artifacts-[a-z0-9]{16} ]] ; then + echo "Bucket was not created by this application. Skipping." + else + while true; do + read -p "Delete deployment artifacts and bucket ($ARTIFACT_BUCKET)? (y/n)" response + case $response in + [Yy]* ) aws s3 rb --force s3://$ARTIFACT_BUCKET; break;; + [Nn]* ) break;; + * ) echo "Response must start with y or n.";; + esac + done + fi + LAYER_BUCKET=$(cat bucket-name.txt)-dotnet-layer + if [[ ! $LAYER_BUCKET =~ lambda-artifacts-[a-z0-9]{16}-dotnet-layer ]] ; then + echo "Layer bucket was not created by this application. Skipping." + else + while true; do + read -p "Delete deployment artifacts and bucket ($LAYER_BUCKET)? (y/n)" response + case $response in + [Yy]* ) aws s3 rb --force s3://$LAYER_BUCKET; break;; + [Nn]* ) break;; + * ) echo "Response must start with y or n.";; + esac + done + fi +fi +rm bucket-name.txt + +while true; do + read -p "Delete function log group (/aws/lambda/blank-csharp)? (y/n)" response + case $response in + [Yy]* ) aws logs delete-log-group --log-group-name /aws/lambda/blank-csharp; break;; + [Nn]* ) break;; + * ) echo "Response must start with y or n.";; + esac +done + +rm -f out.yml out.json layer-arn.txt +rm -rf src/blank-csharp/bin src/blank-csharp/obj \ No newline at end of file diff --git a/sample-apps/blank-csharp-with-layer/README.md b/sample-apps/blank-csharp-with-layer/README.md new file mode 100644 index 00000000..638db2da --- /dev/null +++ b/sample-apps/blank-csharp-with-layer/README.md @@ -0,0 +1,93 @@ +# Blank function with layer (C#) + +![Architecture](/sample-apps/blank-csharp/images/sample-blank-csharp.png) + +The project source includes function code and supporting resources: + +- `src/blank-csharp` - A C# .NET Core function. +- `1-create-bucket.sh`, `2-deploy.sh`, etc. - Shell scripts that use the AWS CLI to deploy and manage the application. + +Use the following instructions to deploy the sample application. For more information on the application's architecture and implementation, see [Managing Spot Instance Requests](https://docs.aws.amazon.com/lambda/latest/dg/services-ec2-tutorial.html) in the developer guide. + +# Requirements +- [.NET Core SDK 8.0](https://dotnet.microsoft.com/download/dotnet-core/8.0) +- [AWS extensions for .NET CLI](https://github.com/aws/aws-extensions-for-dotnet-cli). Specifically, ensure that you have [Amazon.Lambda.Tools](https://github.com/aws/aws-extensions-for-dotnet-cli#aws-lambda-amazonlambdatools) installed. +- The Bash shell. For Linux and macOS, this is included by default. In Windows 10, you can install the [Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows-integrated version of Ubuntu and Bash. +- [The AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html) v1.17 or newer. + +# Setup +Download or clone this repository. + + $ git clone https://github.com/awsdocs/aws-lambda-developer-guide.git + $ cd aws-lambda-developer-guide/sample-apps/blank-csharp + +To create a new bucket for deployment artifacts, run `1-create-bucket-and-role.sh`. + + blank-csharp$ ./1-create-bucket.sh + make_bucket: lambda-artifacts-d7aec9f2022ef2b4 + make_bucket: lambda-artifacts-d7aec9f2022ef2b4-dotnet-layer + { + "Role": { + "Path": "/", + "RoleName": "blank-csharp-role", + "RoleId": "AROA6HOIFXAKKWARP5RSC", + "Arn": "arn:aws:iam::978061735956:role/blank-csharp-role", + "CreateDate": "2023-08-22T18:12:29+00:00", + "AssumeRolePolicyDocument": { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "sts:AssumeRole" + ], + "Principal": { + "Service": [ + "lambda.amazonaws.com" + ] + } + } + ] + } + } + } + +To build a Lambda layer that contains the function's runtime dependencies, run `2-build-layer.sh`. This also uploads the layer to an S3 bucket created by the first script. + + blank-csharp$ ./2-build-layer.sh + +# Deploy +To deploy the application, run `3-deploy.sh`. + + blank-csharp$ ./3-deploy.sh + Amazon Lambda Tools for .NET Core applications (5.8.0) + ... + Created publish archive ... + Creating new Lambda function blank-csharp + New Lambda function created + +This script uses the .NET Amazon Lambda Tools to deploy the Lambda function. It uses the default settings from the `src/aws-lambda-tools-defaults.json` file. + +To invoke the function, run `4-invoke.sh`. + + blank-csharp$ ./4-invoke.sh + { + "StatusCode": 200, + "ExecutedVersion": "$LATEST" + } + {"FunctionCount":13,"TotalCodeSize":598094248} + +Let the script invoke the function a few times and then press `CRTL+C` to exit. + +The application uses AWS X-Ray to trace requests. Open the [X-Ray console](https://console.aws.amazon.com/xray/home#/service-map) to view the service map. The following service map shows the function managing spot instances in Amazon EC2. + +![Service Map](/sample-apps/blank-csharp-with-layer/images/blank-csharp-servicemap.png) + +Choose a node in the main function graph. Then choose **View traces** to see a list of traces. Choose any trace to view a timeline that breaks down the work done by the function. + +![Trace](/sample-apps/blank-csharp-with-layer/images/blank-csharp-trace.png) + +# Cleanup +To delete the application, run the cleanup script. + + blank-csharp$ ./5-cleanup.sh \ No newline at end of file diff --git a/sample-apps/blank-csharp-with-layer/assume-policy.json b/sample-apps/blank-csharp-with-layer/assume-policy.json new file mode 100644 index 00000000..70e75eca --- /dev/null +++ b/sample-apps/blank-csharp-with-layer/assume-policy.json @@ -0,0 +1,16 @@ +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "sts:AssumeRole" + ], + "Principal": { + "Service": [ + "lambda.amazonaws.com" + ] + } + } + ] +} \ No newline at end of file diff --git a/sample-apps/blank-csharp-with-layer/event.json b/sample-apps/blank-csharp-with-layer/event.json new file mode 100644 index 00000000..568467d1 --- /dev/null +++ b/sample-apps/blank-csharp-with-layer/event.json @@ -0,0 +1,20 @@ +{ + "Records": [ + { + "messageId": "19dd0b57-b21e-4ac1-bd88-01bbb068cb78", + "receiptHandle": "MessageReceiptHandle", + "body": "Hello from SQS!", + "attributes": { + "ApproximateReceiveCount": "1", + "SentTimestamp": "1523232000000", + "SenderId": "123456789012", + "ApproximateFirstReceiveTimestamp": "1523232000001" + }, + "messageAttributes": {}, + "md5OfBody": "7b270e59b47ff90a553787216d55d91d", + "eventSource": "aws:sqs", + "eventSourceARN": "arn:aws:sqs:us-west-2:123456789012:MyQueue", + "awsRegion": "us-west-2" + } + ] +} diff --git a/sample-apps/blank-csharp-with-layer/images/blank-csharp-servicemap.png b/sample-apps/blank-csharp-with-layer/images/blank-csharp-servicemap.png new file mode 100644 index 00000000..4bc3364a Binary files /dev/null and b/sample-apps/blank-csharp-with-layer/images/blank-csharp-servicemap.png differ diff --git a/sample-apps/blank-csharp-with-layer/images/blank-csharp-trace.png b/sample-apps/blank-csharp-with-layer/images/blank-csharp-trace.png new file mode 100644 index 00000000..c7a6cbc8 Binary files /dev/null and b/sample-apps/blank-csharp-with-layer/images/blank-csharp-trace.png differ diff --git a/sample-apps/blank-csharp-with-layer/images/sample-blank-csharp.png b/sample-apps/blank-csharp-with-layer/images/sample-blank-csharp.png new file mode 100644 index 00000000..989a8093 Binary files /dev/null and b/sample-apps/blank-csharp-with-layer/images/sample-blank-csharp.png differ diff --git a/sample-apps/blank-csharp-with-layer/src/blank-csharp/Function.cs b/sample-apps/blank-csharp-with-layer/src/blank-csharp/Function.cs new file mode 100644 index 00000000..e3a8db5d --- /dev/null +++ b/sample-apps/blank-csharp-with-layer/src/blank-csharp/Function.cs @@ -0,0 +1,72 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Amazon; +using Amazon.Util; +using Amazon.Lambda; +using Amazon.Lambda.Model; +using Amazon.Lambda.Core; +using Amazon.Lambda.SQSEvents; +using Amazon.XRay.Recorder.Core; +using Amazon.XRay.Recorder.Handlers.AwsSdk; +using System.IO; + +[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] + +namespace blankCsharp +{ + public class Function + { + private AmazonLambdaClient lambdaClient; + + public Function() + { + initialize(); + } + + async void initialize() + { + AWSSDKHandler.RegisterXRayForAllServices(); + lambdaClient = new AmazonLambdaClient(); + await callLambda(); + } + + public async Task FunctionHandler(SQSEvent invocationEvent, ILambdaContext context) + { + GetAccountSettingsResponse accountSettings; + try + { + accountSettings = await callLambda(); + } + catch (AmazonLambdaException ex) + { + throw ex; + } + + AccountUsage accountUsage = accountSettings.AccountUsage; + MemoryStream logData = new MemoryStream(); + StreamReader logDataReader = new StreamReader(logData); + + Amazon.Lambda.Serialization.Json.JsonSerializer serializer = new Amazon.Lambda.Serialization.Json.JsonSerializer(); + + serializer.Serialize(System.Environment.GetEnvironmentVariables(), logData); + LambdaLogger.Log("ENVIRONMENT VARIABLES: " + logDataReader.ReadLine()); + logData.Position = 0; + serializer.Serialize(context, logData); + LambdaLogger.Log("CONTEXT: " + logDataReader.ReadLine()); + logData.Position = 0; + serializer.Serialize(invocationEvent, logData); + LambdaLogger.Log("EVENT: " + logDataReader.ReadLine()); + + return accountUsage; + } + + public async Task callLambda() + { + var request = new GetAccountSettingsRequest(); + var response = await lambdaClient.GetAccountSettingsAsync(request); + return response; + } + } +} diff --git a/sample-apps/blank-csharp-with-layer/src/blank-csharp/aws-lambda-tools-defaults.json b/sample-apps/blank-csharp-with-layer/src/blank-csharp/aws-lambda-tools-defaults.json new file mode 100644 index 00000000..1149f222 --- /dev/null +++ b/sample-apps/blank-csharp-with-layer/src/blank-csharp/aws-lambda-tools-defaults.json @@ -0,0 +1,20 @@ +{ + "Information" : [ + "This file provides default values for the deployment wizard inside Visual Studio and the AWS Lambda commands added to the .NET Core CLI.", + "To learn more about the Lambda commands with the .NET Core CLI execute the following command at the command line in the project root directory.", + + "dotnet lambda help", + + "All the command line options for the Lambda command can be specified in this file." + ], + + "profile":"default", + "region" : "us-east-1", + "configuration" : "Release", + "framework" : "net8.0", + "function-runtime":"dotnet8", + "function-memory-size" : 512, + "function-timeout" : 30, + "function-handler" : "blank-csharp::blankCsharp.Function::FunctionHandler", + "function-role" : "blank-csharp-role" +} diff --git a/sample-apps/blank-csharp-with-layer/src/blank-csharp/blank-csharp.csproj b/sample-apps/blank-csharp-with-layer/src/blank-csharp/blank-csharp.csproj new file mode 100644 index 00000000..4e36256f --- /dev/null +++ b/sample-apps/blank-csharp-with-layer/src/blank-csharp/blank-csharp.csproj @@ -0,0 +1,16 @@ + + + net8.0 + true + Lambda + + + + + + + + + + + \ No newline at end of file diff --git a/sample-apps/blank-csharp-with-layer/test/blank-csharp.Tests/FunctionTest.cs b/sample-apps/blank-csharp-with-layer/test/blank-csharp.Tests/FunctionTest.cs new file mode 100644 index 00000000..76e59c73 --- /dev/null +++ b/sample-apps/blank-csharp-with-layer/test/blank-csharp.Tests/FunctionTest.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +using Amazon.XRay.Recorder.Core; +using Amazon.XRay.Recorder.Core.Internal.Entities; +using Amazon.XRay.Recorder.Core.Exceptions; +using Amazon.XRay.Recorder.Core.Sampling; +using Amazon.XRay.Recorder.Core.Internal.Context; +using Amazon.XRay.Recorder.Core.Internal.Utils; + +using Xunit; +using Amazon.Lambda.Core; +using Amazon.Lambda.SQSEvents; +using Amazon.Lambda.TestUtilities; + +using blankCsharp; + +namespace blankCsharp.Tests +{ + public class TraceFixture : IDisposable + { + private static readonly String _traceHeaderValue = "Root=" + "1-5d66d2fe-8e6fcab805a0833803735bc8" + ";Parent=53995c3f42cd8ad8;Sampled=1"; + + public TraceFixture() + { + Environment.SetEnvironmentVariable(AWSXRayRecorder.LambdaTaskRootKey, "test"); + Environment.SetEnvironmentVariable(AWSXRayRecorder.LambdaTraceHeaderKey, _traceHeaderValue); + Environment.SetEnvironmentVariable("AWS_REGION", "us-east-2"); + } + + public void Dispose() + { + Environment.SetEnvironmentVariable(AWSXRayRecorder.LambdaTaskRootKey, null); + Environment.SetEnvironmentVariable(AWSXRayRecorder.LambdaTraceHeaderKey, null); + Environment.SetEnvironmentVariable("AWS_REGION", null); + } + } + + public class FunctionTest : IClassFixture + { + TraceFixture fixture; + + [Fact] + public void TestFunction() + { + var function = new Function(); + var context = new TestLambdaContext(); + SQSEvent input = new SQSEvent(); + var task = function.FunctionHandler(input, context); + task.Wait(7000); + bool completed = task.IsCompleted; + Assert.True(completed); + } + } +} diff --git a/sample-apps/blank-csharp-with-layer/test/blank-csharp.Tests/blank-csharp.Tests.csproj b/sample-apps/blank-csharp-with-layer/test/blank-csharp.Tests/blank-csharp.Tests.csproj new file mode 100644 index 00000000..d92b11c0 --- /dev/null +++ b/sample-apps/blank-csharp-with-layer/test/blank-csharp.Tests/blank-csharp.Tests.csproj @@ -0,0 +1,15 @@ + + + netcoreapp2.1 + + + + + + + + + + + + \ No newline at end of file diff --git a/sample-apps/blank-csharp/3-invoke.sh b/sample-apps/blank-csharp/3-invoke.sh index 85db0bb9..85ab68d9 100755 --- a/sample-apps/blank-csharp/3-invoke.sh +++ b/sample-apps/blank-csharp/3-invoke.sh @@ -1,9 +1,9 @@ #!/bin/bash set -eo pipefail FUNCTION=$(aws cloudformation describe-stack-resource --stack-name blank-csharp --logical-resource-id function --query 'StackResourceDetail.PhysicalResourceId' --output text) - +if [[ $(aws --version) =~ "aws-cli/2." ]]; then PAYLOAD_PROTOCOL="fileb"; else PAYLOAD_PROTOCOL="file"; fi; while true; do - aws lambda invoke --function-name $FUNCTION --payload file://event.json out.json + aws lambda invoke --function-name $FUNCTION --payload $PAYLOAD_PROTOCOL://event.json out.json cat out.json echo "" sleep 2 diff --git a/sample-apps/blank-csharp/README.md b/sample-apps/blank-csharp/README.md index 891c1a03..a731ea2c 100644 --- a/sample-apps/blank-csharp/README.md +++ b/sample-apps/blank-csharp/README.md @@ -1,66 +1,66 @@ -# Blank function (C#) - -![Architecture](/sample-apps/blank-csharp/images/sample-blank-csharp.png) - -The project source includes function code and supporting resources: - -- `src/blank-csharp` - A C# .NET Core function. -- `template.yml` - An AWS CloudFormation template that creates an application. -- `1-create-bucket.sh`, `2-deploy.sh`, etc. - Shell scripts that use the AWS CLI to deploy and manage the application. - -Use the following instructions to deploy the sample application. For more information on the application's architecture and implementation, see [Managing Spot Instance Requests](https://docs.aws.amazon.com/lambda/latest/dg/services-ec2-tutorial.html) in the developer guide. - -# Requirements -- [.NET Core SDK 3.1](https://nodejs.org/en/download/releases/) -- [AWS extensions for .NET CLI](https://github.com/aws/aws-extensions-for-dotnet-cli) -- The Bash shell. For Linux and macOS, this is included by default. In Windows 10, you can install the [Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows-integrated version of Ubuntu and Bash. -- [The AWS CLI v1](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html). - -# Setup -Download or clone this repository. - - $ git clone https://github.com/awsdocs/aws-lambda-developer-guide.git - $ cd aws-lambda-developer-guide/sample-apps/blank-csharp - -To create a new bucket for deployment artifacts, run `1-create-bucket.sh`. - - blank-csharp$ ./1-create-bucket.sh - make_bucket: lambda-artifacts-a5e491dbb5b22e0d - -# Deploy -To deploy the application, run `2-deploy.sh`. - - blank-csharp$ ./2-deploy.sh - Amazon Lambda Tools for .NET Core applications (4.0.0) - Executing publish command - Uploading to e678bc216e6a0d510d661ca9ae2fd941 1009985 / 1009985.0 (100.00%) - Successfully packaged artifacts and wrote output template to file out.yml. - Waiting for changeset to be created.. - Waiting for stack create/update to complete - Successfully created/updated stack - blank-csharp - -This script uses AWS CloudFormation to deploy the Lambda functions and an IAM role. If the AWS CloudFormation stack that contains the resources already exists, the script updates it with any changes to the template or function code. - -To invoke the function, run `3-invoke.sh`. - - blank-csharp$ ./3-invoke.sh - { - "StatusCode": 200, - "ExecutedVersion": "$LATEST" - } - {"FunctionCount":43,"TotalCodeSize":362867335} - -Let the script invoke the function a few times and then press `CRTL+C` to exit. - -The application uses AWS X-Ray to trace requests. Open the [X-Ray console](https://console.aws.amazon.com/xray/home#/service-map) to view the service map. The following service map shows the function managing spot instances in Amazon EC2. - -![Service Map](/sample-apps/blank-csharp/images/blank-csharp-servicemap.png) - -Choose a node in the main function graph. Then choose **View traces** to see a list of traces. Choose any trace to view a timeline that breaks down the work done by the function. - -![Trace](/sample-apps/blank-csharp/images/blank-csharp-trace.png) - -# Cleanup -To delete the application, run the cleanup script. - - blank-csharp$ ./4-cleanup.sh +# Blank function (C#) + +![Architecture](/sample-apps/blank-csharp/images/sample-blank-csharp.png) + +The project source includes function code and supporting resources: + +- `src/blank-csharp` - A C# .NET Core function. +- `template.yml` - An AWS CloudFormation template that creates an application. +- `1-create-bucket.sh`, `2-deploy.sh`, etc. - Shell scripts that use the AWS CLI to deploy and manage the application. + +Use the following instructions to deploy the sample application. For more information on the application's architecture and implementation, see [Managing Spot Instance Requests](https://docs.aws.amazon.com/lambda/latest/dg/services-ec2-tutorial.html) in the developer guide. + +# Requirements +- [.NET Core SDK 8.0](https://dotnet.microsoft.com/download/dotnet-core/8.0) +- [AWS extensions for .NET CLI](https://github.com/aws/aws-extensions-for-dotnet-cli) +- The Bash shell. For Linux and macOS, this is included by default. In Windows 10, you can install the [Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows-integrated version of Ubuntu and Bash. +- [The AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html) v1.17 or newer. + +# Setup +Download or clone this repository. + + $ git clone https://github.com/awsdocs/aws-lambda-developer-guide.git + $ cd aws-lambda-developer-guide/sample-apps/blank-csharp + +To create a new bucket for deployment artifacts, run `1-create-bucket.sh`. + + blank-csharp$ ./1-create-bucket.sh + make_bucket: lambda-artifacts-a5e491dbb5b22e0d + +# Deploy +To deploy the application, run `2-deploy.sh`. + + blank-csharp$ ./2-deploy.sh + Amazon Lambda Tools for .NET Core applications (4.0.0) + Executing publish command + Uploading to e678bc216e6a0d510d661ca9ae2fd941 1009985 / 1009985.0 (100.00%) + Successfully packaged artifacts and wrote output template to file out.yml. + Waiting for changeset to be created.. + Waiting for stack create/update to complete + Successfully created/updated stack - blank-csharp + +This script uses AWS CloudFormation to deploy the Lambda functions and an IAM role. If the AWS CloudFormation stack that contains the resources already exists, the script updates it with any changes to the template or function code. + +To invoke the function, run `3-invoke.sh`. + + blank-csharp$ ./3-invoke.sh + { + "StatusCode": 200, + "ExecutedVersion": "$LATEST" + } + {"FunctionCount":43,"TotalCodeSize":362867335} + +Let the script invoke the function a few times and then press `CRTL+C` to exit. + +The application uses AWS X-Ray to trace requests. Open the [X-Ray console](https://console.aws.amazon.com/xray/home#/service-map) to view the service map. The following service map shows the function managing spot instances in Amazon EC2. + +![Service Map](/sample-apps/blank-csharp/images/blank-csharp-servicemap.png) + +Choose a node in the main function graph. Then choose **View traces** to see a list of traces. Choose any trace to view a timeline that breaks down the work done by the function. + +![Trace](/sample-apps/blank-csharp/images/blank-csharp-trace.png) + +# Cleanup +To delete the application, run the cleanup script. + + blank-csharp$ ./4-cleanup.sh \ No newline at end of file diff --git a/sample-apps/blank-csharp/src/blank-csharp/Function.cs b/sample-apps/blank-csharp/src/blank-csharp/Function.cs index a97a3199..e3a8db5d 100644 --- a/sample-apps/blank-csharp/src/blank-csharp/Function.cs +++ b/sample-apps/blank-csharp/src/blank-csharp/Function.cs @@ -10,8 +10,7 @@ using Amazon.Lambda.SQSEvents; using Amazon.XRay.Recorder.Core; using Amazon.XRay.Recorder.Handlers.AwsSdk; -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; +using System.IO; [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] @@ -19,41 +18,55 @@ namespace blankCsharp { public class Function { - private static AmazonLambdaClient lambdaClient; - - static Function() { - initialize(); - } - - static async void initialize() { - AWSSDKHandler.RegisterXRayForAllServices(); - lambdaClient = new AmazonLambdaClient(); - await callLambda(); - } - - public async Task FunctionHandler(SQSEvent invocationEvent, ILambdaContext context) - { - GetAccountSettingsResponse accountSettings; - try - { - accountSettings = await callLambda(); - } - catch (AmazonLambdaException ex) - { - throw ex; - } - AccountUsage accountUsage = accountSettings.AccountUsage; - LambdaLogger.Log("ENVIRONMENT VARIABLES: " + JsonConvert.SerializeObject(System.Environment.GetEnvironmentVariables())); - LambdaLogger.Log("CONTEXT: " + JsonConvert.SerializeObject(context)); - LambdaLogger.Log("EVENT: " + JsonConvert.SerializeObject(invocationEvent)); - return accountUsage; - } - - public static async Task callLambda() - { - var request = new GetAccountSettingsRequest(); - var response = await lambdaClient.GetAccountSettingsAsync(request); - return response; - } + private AmazonLambdaClient lambdaClient; + + public Function() + { + initialize(); + } + + async void initialize() + { + AWSSDKHandler.RegisterXRayForAllServices(); + lambdaClient = new AmazonLambdaClient(); + await callLambda(); + } + + public async Task FunctionHandler(SQSEvent invocationEvent, ILambdaContext context) + { + GetAccountSettingsResponse accountSettings; + try + { + accountSettings = await callLambda(); + } + catch (AmazonLambdaException ex) + { + throw ex; + } + + AccountUsage accountUsage = accountSettings.AccountUsage; + MemoryStream logData = new MemoryStream(); + StreamReader logDataReader = new StreamReader(logData); + + Amazon.Lambda.Serialization.Json.JsonSerializer serializer = new Amazon.Lambda.Serialization.Json.JsonSerializer(); + + serializer.Serialize(System.Environment.GetEnvironmentVariables(), logData); + LambdaLogger.Log("ENVIRONMENT VARIABLES: " + logDataReader.ReadLine()); + logData.Position = 0; + serializer.Serialize(context, logData); + LambdaLogger.Log("CONTEXT: " + logDataReader.ReadLine()); + logData.Position = 0; + serializer.Serialize(invocationEvent, logData); + LambdaLogger.Log("EVENT: " + logDataReader.ReadLine()); + + return accountUsage; + } + + public async Task callLambda() + { + var request = new GetAccountSettingsRequest(); + var response = await lambdaClient.GetAccountSettingsAsync(request); + return response; + } } } diff --git a/sample-apps/blank-csharp/src/blank-csharp/aws-lambda-tools-defaults.json b/sample-apps/blank-csharp/src/blank-csharp/aws-lambda-tools-defaults.json index 9e276d0c..8a9c7869 100644 --- a/sample-apps/blank-csharp/src/blank-csharp/aws-lambda-tools-defaults.json +++ b/sample-apps/blank-csharp/src/blank-csharp/aws-lambda-tools-defaults.json @@ -1,19 +1,19 @@ -{ - "Information" : [ - "This file provides default values for the deployment wizard inside Visual Studio and the AWS Lambda commands added to the .NET Core CLI.", - "To learn more about the Lambda commands with the .NET Core CLI execute the following command at the command line in the project root directory.", - - "dotnet lambda help", - - "All the command line options for the Lambda command can be specified in this file." - ], - - "profile":"default", - "region" : "us-east-2", - "configuration" : "Release", - "framework" : "netcoreapp3.1", - "function-runtime":"dotnetcore3.1", - "function-memory-size" : 512, - "function-timeout" : 30, - "function-handler" : "blank-csharp::blankCsharp.Function::FunctionHandler" -} +{ + "Information" : [ + "This file provides default values for the deployment wizard inside Visual Studio and the AWS Lambda commands added to the .NET Core CLI.", + "To learn more about the Lambda commands with the .NET Core CLI execute the following command at the command line in the project root directory.", + + "dotnet lambda help", + + "All the command line options for the Lambda command can be specified in this file." + ], + + "profile":"default", + "region" : "us-east-2", + "configuration" : "Release", + "framework" : "net8.0", + "function-runtime":"dotnet8", + "function-memory-size" : 512, + "function-timeout" : 30, + "function-handler" : "blank-csharp::blankCsharp.Function::FunctionHandler" +} \ No newline at end of file diff --git a/sample-apps/blank-csharp/src/blank-csharp/blank-csharp.csproj b/sample-apps/blank-csharp/src/blank-csharp/blank-csharp.csproj index edd8b786..4e36256f 100644 --- a/sample-apps/blank-csharp/src/blank-csharp/blank-csharp.csproj +++ b/sample-apps/blank-csharp/src/blank-csharp/blank-csharp.csproj @@ -1,17 +1,16 @@ - - - netcoreapp3.1 - true - Lambda - - - - - - - - - - - + + + net8.0 + true + Lambda + + + + + + + + + + \ No newline at end of file diff --git a/sample-apps/blank-csharp/template.yml b/sample-apps/blank-csharp/template.yaml similarity index 74% rename from sample-apps/blank-csharp/template.yml rename to sample-apps/blank-csharp/template.yaml index 190dd823..c92e6a35 100644 --- a/sample-apps/blank-csharp/template.yml +++ b/sample-apps/blank-csharp/template.yaml @@ -1,19 +1,19 @@ -AWSTemplateFormatVersion: '2010-09-09' -Transform: 'AWS::Serverless-2016-10-31' -Description: An AWS Lambda application that calls the Lambda API. -Resources: - function: - Type: AWS::Serverless::Function - Properties: - Handler: blank-csharp::blankCsharp.Function::FunctionHandler - Runtime: dotnetcore3.1 - CodeUri: src/blank-csharp/bin/Release/netcoreapp3.1/blank-csharp.zip - Description: Call the AWS Lambda API - MemorySize: 256 - Timeout: 9 - # Function's execution role - Policies: - - AWSLambdaBasicExecutionRole - - AWSLambdaReadOnlyAccess - - AWSXrayWriteOnlyAccess - Tracing: Active +AWSTemplateFormatVersion: '2010-09-09' +Transform: 'AWS::Serverless-2016-10-31' +Description: An AWS Lambda application that calls the Lambda API. +Resources: + function: + Type: AWS::Serverless::Function + Properties: + Handler: blank-csharp::blankCsharp.Function::FunctionHandler + Runtime: dotnet8 + CodeUri: src/blank-csharp/bin/Release/net8.0/blank-csharp.zip + Description: Call the AWS Lambda API + MemorySize: 256 + Timeout: 9 + # Function's execution role + Policies: + - AWSLambdaBasicExecutionRole + - AWSLambda_ReadOnlyAccess + - AWSXrayWriteOnlyAccess + Tracing: Active \ No newline at end of file diff --git a/sample-apps/blank-go/2-deploy.sh b/sample-apps/blank-go/2-deploy.sh index 5530600f..0141912b 100755 --- a/sample-apps/blank-go/2-deploy.sh +++ b/sample-apps/blank-go/2-deploy.sh @@ -2,7 +2,7 @@ set -eo pipefail ARTIFACT_BUCKET=$(cat bucket-name.txt) cd function -GOOS=linux go build main.go +GOOS=linux go build -tags lambda.norpc -o bootstrap main.go cd ../ aws cloudformation package --template-file template.yml --s3-bucket $ARTIFACT_BUCKET --output-template-file out.yml aws cloudformation deploy --template-file out.yml --stack-name blank-go --capabilities CAPABILITY_NAMED_IAM diff --git a/sample-apps/blank-go/3-invoke.sh b/sample-apps/blank-go/3-invoke.sh index 7c7dcfab..58868b77 100755 --- a/sample-apps/blank-go/3-invoke.sh +++ b/sample-apps/blank-go/3-invoke.sh @@ -3,7 +3,7 @@ set -eo pipefail FUNCTION=$(aws cloudformation describe-stack-resource --stack-name blank-go --logical-resource-id function --query 'StackResourceDetail.PhysicalResourceId' --output text) while true; do - aws lambda invoke --function-name $FUNCTION --payload file://event.json out.json + aws lambda invoke --function-name $FUNCTION --payload fileb://event.json out.json cat out.json echo "" sleep 2 diff --git a/sample-apps/blank-go/README.md b/sample-apps/blank-go/README.md index fc097d12..cd77d84a 100644 --- a/sample-apps/blank-go/README.md +++ b/sample-apps/blank-go/README.md @@ -13,7 +13,7 @@ Use the following instructions to deploy the sample application. # Requirements - [Go executable](https://golang.org/dl/). - The Bash shell. For Linux and macOS, this is included by default. In Windows 10, you can install the [Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows-integrated version of Ubuntu and Bash. -- [The AWS CLI v1](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html). +- [The AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html) v1.17 or newer. # Setup Download or clone this repository. diff --git a/sample-apps/blank-go/function/go.mod b/sample-apps/blank-go/function/go.mod index d1111739..c06ee314 100644 --- a/sample-apps/blank-go/function/go.mod +++ b/sample-apps/blank-go/function/go.mod @@ -1,8 +1,10 @@ module github.com/awsdocs/aws-lambda-developer-guide/sample-apps/blank-go -go 1.14 +go 1.20 require ( - github.com/aws/aws-lambda-go v1.15.0 - github.com/aws/aws-sdk-go v1.29.33 +github.com/aws/aws-lambda-go v1.43.0 +github.com/aws/aws-sdk-go v1.49.12 ) + +require github.com/jmespath/go-jmespath v0.4.0 // indirect \ No newline at end of file diff --git a/sample-apps/blank-go/function/go.sum b/sample-apps/blank-go/function/go.sum index fa3ee7b1..263508e0 100644 --- a/sample-apps/blank-go/function/go.sum +++ b/sample-apps/blank-go/function/go.sum @@ -1,23 +1,20 @@ -github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/aws/aws-lambda-go v1.15.0 h1:QAhRWvXttl8TtBsODN+NzZETkci2mdN/paJ0+1hX/so= -github.com/aws/aws-lambda-go v1.15.0/go.mod h1:FEwgPLE6+8wcGBTe5cJN3JWurd1Ztm9zN4jsXsjzKKw= -github.com/aws/aws-sdk-go v1.29.33 h1:WP85+WHalTFQR2wYp5xR2sjiVAZXew2bBQXGU1QJBXI= -github.com/aws/aws-sdk-go v1.29.33/go.mod h1:1KvfttTE3SPKMpo8g2c6jL3ZKfXtFvKscTgahTma5Xg= -github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= +github.com/aws/aws-lambda-go v1.43.0 h1:Tdu7SnMB5bD+CbdnSq1Dg4sM68vEuGIDcQFZ+IjUfx0= +github.com/aws/aws-lambda-go v1.43.0/go.mod h1:dpMpZgvWx5vuQJfBt0zqBha60q7Dd7RfgJv23DymV8A= +github.com/aws/aws-sdk-go v1.49.12 h1:SbGHDdMjtuTL8zpRXKjvIvQHLt9cCqcxcHoJps23WxI= +github.com/aws/aws-sdk-go v1.49.12/go.mod h1:LF8svs817+Nz+DmiMQKTO3ubZ/6IaTpq3TjupRn3Eqk= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= -github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af h1:pmfjZENx5imkbgOkpRUYLnmbU7UEFbjtDA2hxJ1ichM= -github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= +github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= +github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8= +github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/urfave/cli/v2 v2.1.1/go.mod h1:SE9GqnLQmjVa0iPEY0f1w3ygNIYcIJ0OKPMoW2caLfQ= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +github.com/stretchr/testify v1.7.2 h1:4jaiDzPyXQvSd7D0EjG45355tLlV3VOECpq10pLC+8s= +golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= +golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= \ No newline at end of file diff --git a/sample-apps/blank-go/function/main.go b/sample-apps/blank-go/function/main.go index fb45d288..04d89f09 100644 --- a/sample-apps/blank-go/function/main.go +++ b/sample-apps/blank-go/function/main.go @@ -1,57 +1,53 @@ package main import ( - "os" - "log" - "context" - "encoding/json" - runtime "github.com/aws/aws-lambda-go/lambda" - "github.com/aws/aws-lambda-go/events" - "github.com/aws/aws-lambda-go/lambdacontext" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/lambda" + "context" + "encoding/json" + "github.com/aws/aws-lambda-go/events" + runtime "github.com/aws/aws-lambda-go/lambda" + "github.com/aws/aws-lambda-go/lambdacontext" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/lambda" + "log" + "os" ) var client = lambda.New(session.New()) -func init() { - callLambda() -} - func callLambda() (string, error) { - input := &lambda.GetAccountSettingsInput{} - req, resp := client.GetAccountSettingsRequest(input) - err := req.Send() - output, _ := json.Marshal(resp.AccountUsage) - return string(output), err + input := &lambda.GetAccountSettingsInput{} + req, resp := client.GetAccountSettingsRequest(input) + err := req.Send() + output, _ := json.Marshal(resp.AccountUsage) + return string(output), err } func handleRequest(ctx context.Context, event events.SQSEvent) (string, error) { - // event - eventJson, _ := json.MarshalIndent(event, "", " ") - log.Printf("EVENT: %s", eventJson) - // environment variables - log.Printf("REGION: %s", os.Getenv("AWS_REGION")) - log.Println("ALL ENV VARS:") - for _, element := range os.Environ() { - log.Println(element) - } - // request context - lc, _ := lambdacontext.FromContext(ctx) - log.Printf("REQUEST ID: %s", lc.AwsRequestID) - // global variable - log.Printf("FUNCTION NAME: %s", lambdacontext.FunctionName) - // context method - deadline, _ := ctx.Deadline() - log.Printf("DEADLINE: %s", deadline) - // AWS SDK call - usage, err := callLambda() - if err != nil { - return "ERROR", err - } - return usage, nil + // event + eventJson, _ := json.MarshalIndent(event, "", " ") + log.Printf("EVENT: %s", eventJson) + // environment variables + log.Printf("REGION: %s", os.Getenv("AWS_REGION")) + log.Println("ALL ENV VARS:") + for _, element := range os.Environ() { + log.Println(element) + } + // request context + lc, _ := lambdacontext.FromContext(ctx) + log.Printf("REQUEST ID: %s", lc.AwsRequestID) + // global variable + log.Printf("FUNCTION NAME: %s", lambdacontext.FunctionName) + // context method + deadline, _ := ctx.Deadline() + log.Printf("DEADLINE: %s", deadline) + // AWS SDK call + usage, err := callLambda() + if err != nil { + return "ERROR", err + } + return usage, nil } func main() { - runtime.Start(handleRequest) -} \ No newline at end of file + runtime.Start(handleRequest) +} diff --git a/sample-apps/blank-go/function/main_test.go b/sample-apps/blank-go/function/main_test.go index bf192bd6..277a3cf6 100644 --- a/sample-apps/blank-go/function/main_test.go +++ b/sample-apps/blank-go/function/main_test.go @@ -33,7 +33,7 @@ func TestMain(t *testing.T) { } t.Log(result) if !strings.Contains(result, "FunctionCount") { - t.Errorf("Output does not contain FunctionCode.") + t.Errorf("Output does not contain FunctionCount.") } } func ReadJSONFromFile(t *testing.T, inputFile string) []byte { diff --git a/sample-apps/blank-go/template.yml b/sample-apps/blank-go/template.yml index 007eb42b..51552935 100644 --- a/sample-apps/blank-go/template.yml +++ b/sample-apps/blank-go/template.yml @@ -4,15 +4,16 @@ Description: An AWS Lambda application that calls the Lambda API. Resources: function: Type: AWS::Serverless::Function + Metadata: + BuildMethod: go1.x Properties: - Handler: main - Runtime: go1.x - CodeUri: function/. - Description: Call the AWS Lambda API + CodeUri: function/ # folder where your main program resides + Handler: bootstrap + Runtime: provided.al2023 Timeout: 5 # Function's execution role Policies: - AWSLambdaBasicExecutionRole - - AWSLambdaReadOnlyAccess + - AWSLambda_ReadOnlyAccess - AWSXrayWriteOnlyAccess - Tracing: Active + Tracing: Active \ No newline at end of file diff --git a/sample-apps/blank-java/2-build-layer.sh b/sample-apps/blank-java/2-build-layer.sh index 9a1dd8cd..144dd65b 100755 --- a/sample-apps/blank-java/2-build-layer.sh +++ b/sample-apps/blank-java/2-build-layer.sh @@ -1,4 +1,13 @@ #!/bin/bash set -eo pipefail -gradle -q packageLibs -mv build/distributions/blank-java.zip build/blank-java-lib.zip \ No newline at end of file + +if [ $1 ] +then + if [ $1 = mvn ] + then + mvn prepare-package + fi +else + gradle -q packageLibs + mv build/distributions/blank-java.zip build/blank-java-lib.zip +fi \ No newline at end of file diff --git a/sample-apps/blank-java/4-invoke.sh b/sample-apps/blank-java/4-invoke.sh index 2186f191..80939fa9 100755 --- a/sample-apps/blank-java/4-invoke.sh +++ b/sample-apps/blank-java/4-invoke.sh @@ -3,7 +3,7 @@ set -eo pipefail FUNCTION=$(aws cloudformation describe-stack-resource --stack-name blank-java --logical-resource-id function --query 'StackResourceDetail.PhysicalResourceId' --output text) while true; do - aws lambda invoke --function-name $FUNCTION --payload file://event.json out.json + aws lambda invoke --function-name $FUNCTION --payload fileb://event.json out.json cat out.json echo "" sleep 2 diff --git a/sample-apps/blank-java/README.md b/sample-apps/blank-java/README.md index ec93d04d..2c36ddc6 100644 --- a/sample-apps/blank-java/README.md +++ b/sample-apps/blank-java/README.md @@ -14,10 +14,11 @@ The project source includes function code and supporting resources: Use the following instructions to deploy the sample application. # Requirements +- An AWS account. - [Java 8 runtime environment (SE JRE)](https://www.oracle.com/java/technologies/javase-downloads.html) - [Gradle 5](https://gradle.org/releases/) or [Maven 3](https://maven.apache.org/docs/history.html) - The Bash shell. For Linux and macOS, this is included by default. In Windows 10, you can install the [Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows-integrated version of Ubuntu and Bash. -- [The AWS CLI v1](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html). +- [The AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html) v1.17 or newer. # Setup Download or clone this repository. @@ -34,6 +35,10 @@ To build a Lambda layer that contains the function's runtime dependencies, run ` blank-java$ ./2-build-layer.sh +You can also run this commnand with Maven. To use Maven, add `mvn` to the command. + + blank-java$ ./2-build-layer.sh mvn + # Deploy To deploy the application, run `3-deploy.sh`. @@ -46,7 +51,7 @@ To deploy the application, run `3-deploy.sh`. This script uses AWS CloudFormation to deploy the Lambda functions and an IAM role. If the AWS CloudFormation stack that contains the resources already exists, the script updates it with any changes to the template or function code. -You can also build the application with Maven. To use maven, add `mvn` to the command. +You can also build the application with Maven. To use Maven, add `mvn` to the command. java-basic$ ./3-deploy.sh mvn [INFO] Scanning for projects... diff --git a/sample-apps/blank-java/build.gradle b/sample-apps/blank-java/build.gradle index 4ef9ff7b..77ecd978 100644 --- a/sample-apps/blank-java/build.gradle +++ b/sample-apps/blank-java/build.gradle @@ -7,22 +7,16 @@ repositories { } dependencies { - implementation platform('software.amazon.awssdk:bom:2.10.73') + implementation platform('software.amazon.awssdk:bom:2.10.72') implementation platform('com.amazonaws:aws-xray-recorder-sdk-bom:2.4.0') implementation 'software.amazon.awssdk:lambda' implementation 'com.amazonaws:aws-xray-recorder-sdk-core' - implementation 'com.amazonaws:aws-xray-recorder-sdk-aws-sdk-core' - implementation 'com.amazonaws:aws-xray-recorder-sdk-aws-sdk-v2' - implementation 'com.amazonaws:aws-xray-recorder-sdk-aws-sdk-v2-instrumentor' - implementation 'com.amazonaws:aws-lambda-java-core:1.2.0' - implementation 'com.amazonaws:aws-lambda-java-events:2.2.7' - implementation 'com.google.code.gson:gson:2.8.6' - implementation 'org.apache.logging.log4j:log4j-api:2.13.0' - implementation 'org.apache.logging.log4j:log4j-core:2.13.0' - runtimeOnly 'org.apache.logging.log4j:log4j-slf4j18-impl:2.13.0' - runtimeOnly 'com.amazonaws:aws-lambda-java-log4j2:1.1.0' - testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0' - testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.6.0' + implementation 'com.amazonaws:aws-lambda-java-core:1.2.1' + implementation 'com.amazonaws:aws-lambda-java-events:2.2.9' + implementation 'org.slf4j:slf4j-nop:2.0.6' + testImplementation 'com.amazonaws:aws-lambda-java-tests:1.1.1' + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.2' + testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.2' } test { @@ -53,8 +47,8 @@ task packageSkinny(type: Zip) { } java { - sourceCompatibility = JavaVersion.VERSION_1_8 - targetCompatibility = JavaVersion.VERSION_1_8 + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 } build.dependsOn packageSkinny diff --git a/sample-apps/blank-java/event.json b/sample-apps/blank-java/event.json index 568467d1..a5fb7093 100644 --- a/sample-apps/blank-java/event.json +++ b/sample-apps/blank-java/event.json @@ -1,20 +1,5 @@ { - "Records": [ - { - "messageId": "19dd0b57-b21e-4ac1-bd88-01bbb068cb78", - "receiptHandle": "MessageReceiptHandle", - "body": "Hello from SQS!", - "attributes": { - "ApproximateReceiveCount": "1", - "SentTimestamp": "1523232000000", - "SenderId": "123456789012", - "ApproximateFirstReceiveTimestamp": "1523232000001" - }, - "messageAttributes": {}, - "md5OfBody": "7b270e59b47ff90a553787216d55d91d", - "eventSource": "aws:sqs", - "eventSourceARN": "arn:aws:sqs:us-west-2:123456789012:MyQueue", - "awsRegion": "us-west-2" - } - ] + "key1": "value1", + "key2": "value2", + "key3": "value3" } diff --git a/sample-apps/blank-java/pom.xml b/sample-apps/blank-java/pom.xml index f339eeb2..851541ae 100644 --- a/sample-apps/blank-java/pom.xml +++ b/sample-apps/blank-java/pom.xml @@ -8,44 +8,24 @@ blank-java-function UTF-8 - 1.8 - 1.8 + 11 + 11 com.amazonaws aws-lambda-java-core - 1.2.0 + 1.2.1 com.amazonaws aws-lambda-java-events - 2.2.7 + 2.2.9 - com.amazonaws - aws-lambda-java-log4j2 - 1.1.0 - - - com.google.code.gson - gson - 2.8.6 - - - org.apache.logging.log4j - log4j-api - 2.13.0 - - - org.apache.logging.log4j - log4j-core - 2.13.0 - - - org.apache.logging.log4j - log4j-slf4j18-impl - 2.13.0 + org.slf4j + slf4j-nop + 2.0.6 software.amazon.awssdk @@ -57,34 +37,24 @@ aws-xray-recorder-sdk-core 2.4.0 - - com.amazonaws - aws-xray-recorder-sdk-aws-sdk-core - 2.4.0 - - - com.amazonaws - aws-xray-recorder-sdk-aws-sdk-v2 - 2.4.0 - - - com.amazonaws - aws-xray-recorder-sdk-aws-sdk-v2-instrumentor - 2.4.0 - org.junit.jupiter junit-jupiter-api - 5.6.0 + 5.8.2 test org.junit.jupiter junit-jupiter-engine - 5.6.0 + 5.8.2 test - + + com.amazonaws + aws-lambda-java-tests + 1.1.1 + test + @@ -99,6 +69,17 @@ 3.2.2 false + + + *:* + + module-info.class + META-INF/* + META-INF/versions/** + META-INF/services/** + + + @@ -106,29 +87,54 @@ shade + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-dependencies + prepare-package + + copy-dependencies + + + + ${project.build.directory}/classes/java/lib + + runtime + test + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + prepare-package + + single + - - - - + false + + zip.xml + - - - com.github.edwgiz - maven-shade-plugin.log4j2-cachefile-transformer - 2.13.0 - - org.apache.maven.plugins maven-compiler-plugin 3.8.1 - 1.8 - 1.8 + 11 + 11 diff --git a/sample-apps/blank-java/src/main/java/example/Handler.java b/sample-apps/blank-java/src/main/java/example/Handler.java index b0962713..296b5eff 100644 --- a/sample-apps/blank-java/src/main/java/example/Handler.java +++ b/sample-apps/blank-java/src/main/java/example/Handler.java @@ -3,63 +3,30 @@ import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.LambdaLogger; import com.amazonaws.services.lambda.runtime.RequestHandler; -import com.amazonaws.services.lambda.runtime.events.SQSEvent; -import com.amazonaws.services.lambda.runtime.events.SQSEvent.SQSMessage; -import software.amazon.awssdk.services.lambda.model.GetAccountSettingsRequest; +import java.util.Map; + +import software.amazon.awssdk.services.lambda.LambdaClient; import software.amazon.awssdk.services.lambda.model.GetAccountSettingsResponse; -import software.amazon.awssdk.services.lambda.model.ServiceException; -import software.amazon.awssdk.services.lambda.LambdaAsyncClient; -import software.amazon.awssdk.services.lambda.model.AccountUsage; +import software.amazon.awssdk.services.lambda.model.LambdaException; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +// Handler value: example.Handler +public class Handler implements RequestHandler, String> { -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; + private static final LambdaClient lambdaClient = LambdaClient.builder().build(); -import java.lang.StringBuilder; -import java.util.Map; -import java.util.List; -import java.util.concurrent.CompletableFuture; + @Override + public String handleRequest(Map event, Context context) { -// Handler value: example.Handler -public class Handler implements RequestHandler{ - private static final Logger logger = LoggerFactory.getLogger(Handler.class); - private static final Gson gson = new GsonBuilder().setPrettyPrinting().create(); - private static final LambdaAsyncClient lambdaClient = LambdaAsyncClient.create(); - public Handler(){ - CompletableFuture accountSettings = lambdaClient.getAccountSettings(GetAccountSettingsRequest.builder().build()); - try { - GetAccountSettingsResponse settings = accountSettings.get(); - } catch(Exception e) { - e.getStackTrace(); - } - } - @Override - public String handleRequest(SQSEvent event, Context context) - { - String response = new String(); - // call Lambda API - logger.info("Getting account settings"); - CompletableFuture accountSettings = - lambdaClient.getAccountSettings(GetAccountSettingsRequest.builder().build()); - // log execution details - logger.info("ENVIRONMENT VARIABLES: {}", gson.toJson(System.getenv())); - logger.info("CONTEXT: {}", gson.toJson(context)); - logger.info("EVENT: {}", gson.toJson(event)); - // process event - for(SQSMessage msg : event.getRecords()){ - logger.info(msg.getBody()); - } - // process Lambda API response - try { - GetAccountSettingsResponse settings = accountSettings.get(); - response = gson.toJson(settings.accountUsage()); - logger.info("Account usage: {}", response); - } catch(Exception e) { - e.getStackTrace(); + LambdaLogger logger = context.getLogger(); + logger.log("Handler invoked"); + + GetAccountSettingsResponse response = null; + try { + response = lambdaClient.getAccountSettings(); + } catch(LambdaException e) { + logger.log(e.getMessage()); + } + return response != null ? "Total code size for your account is " + response.accountLimit().totalCodeSize() + " bytes" : "Error"; } - return response; - } -} \ No newline at end of file +} diff --git a/sample-apps/blank-java/src/main/resources/log4j2.xml b/sample-apps/blank-java/src/main/resources/log4j2.xml deleted file mode 100644 index b9a6c317..00000000 --- a/sample-apps/blank-java/src/main/resources/log4j2.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - %d{yyyy-MM-dd HH:mm:ss} %X{AWSRequestId} %-5p %c{1} - %m%n - - - - - - - - - - - \ No newline at end of file diff --git a/sample-apps/blank-java/src/test/java/example/InvokeTest.java b/sample-apps/blank-java/src/test/java/example/InvokeTest.java index c65b9371..ecf44a15 100644 --- a/sample-apps/blank-java/src/test/java/example/InvokeTest.java +++ b/sample-apps/blank-java/src/test/java/example/InvokeTest.java @@ -1,71 +1,33 @@ package example; -import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.LambdaLogger; -import com.amazonaws.services.lambda.runtime.RequestHandler; -import com.amazonaws.services.lambda.runtime.events.SQSEvent; -import com.amazonaws.services.lambda.runtime.events.SQSEvent.SQSMessage; +import com.amazonaws.services.lambda.runtime.tests.annotations.Event; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.List; -import java.util.ArrayList; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.stream.Stream; +import java.util.Map; import com.amazonaws.xray.AWSXRay; import com.amazonaws.xray.AWSXRayRecorderBuilder; import com.amazonaws.xray.strategy.sampling.NoSamplingStrategy; class InvokeTest { - private static final Logger logger = LoggerFactory.getLogger(InvokeTest.class); - Gson gson = new GsonBuilder() - .registerTypeAdapter(SQSEvent.class, new SQSEventDeserializer()) - .setPrettyPrinting() - .create(); public InvokeTest() { - AWSXRayRecorderBuilder builder = AWSXRayRecorderBuilder.standard(); - builder.withSamplingStrategy(new NoSamplingStrategy()); - AWSXRay.setGlobalRecorder(builder.build()); - } - - @Test - void invokeTest() { - AWSXRay.beginSegment("blank-java-test"); - String path = "src/test/resources/event.json"; - String eventString = loadJsonFile(path); - SQSEvent event = gson.fromJson(eventString, SQSEvent.class); - Context context = new TestContext(); - String requestId = context.getAwsRequestId(); - Handler handler = new Handler(); - String result = handler.handleRequest(event, context); - assertTrue(result.contains("totalCodeSize")); - AWSXRay.endSegment(); + AWSXRayRecorderBuilder builder = AWSXRayRecorderBuilder.standard(); + builder.withSamplingStrategy(new NoSamplingStrategy()); + AWSXRay.setGlobalRecorder(builder.build()); } - private static String loadJsonFile(String path) - { - StringBuilder stringBuilder = new StringBuilder(); - try (Stream stream = Files.lines( Paths.get(path), StandardCharsets.UTF_8)) - { - stream.forEach(s -> stringBuilder.append(s)); - } - catch (IOException e) - { - e.printStackTrace(); - } - return stringBuilder.toString(); + @ParameterizedTest + @Event(value = "event.json", type = Map.class) + void invokeTest(Map event) { + AWSXRay.beginSegment("blank-java-test"); + Context context = new TestContext(); + Handler handler = new Handler(); + String result = handler.handleRequest(event, context); + assertTrue(result.contains("Total code size for your account")); + AWSXRay.endSegment(); } } diff --git a/sample-apps/blank-java/src/test/java/example/SQSEventDeserializer.java b/sample-apps/blank-java/src/test/java/example/SQSEventDeserializer.java deleted file mode 100644 index c2576307..00000000 --- a/sample-apps/blank-java/src/test/java/example/SQSEventDeserializer.java +++ /dev/null @@ -1,42 +0,0 @@ -package example; - -import com.amazonaws.services.lambda.runtime.LambdaLogger; -import com.amazonaws.services.lambda.runtime.RequestHandler; -import com.amazonaws.services.lambda.runtime.events.SQSEvent; -import com.amazonaws.services.lambda.runtime.events.SQSEvent.SQSMessage; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonParseException; -import com.google.gson.JsonDeserializer; -import com.google.gson.reflect.TypeToken; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.List; -import java.util.ArrayList; -import java.lang.reflect.Type; - -public class SQSEventDeserializer implements JsonDeserializer { - private static final Logger logger = LoggerFactory.getLogger(InvokeTest.class); - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - Type sqsMessageArray = new TypeToken>(){}.getType(); - - @Override - public SQSEvent deserialize(JsonElement eventJson, Type typeOfT, JsonDeserializationContext context) - throws JsonParseException { - SQSEvent event = new SQSEvent(); - logger.info("DESERIALIZING TEST EVENT"); - logger.info("EVENT JSON: " + eventJson.toString()); - // Records key is capitalized in test event, but lowercase in type - JsonArray recordsArray = eventJson.getAsJsonObject().get("Records").getAsJsonArray(); - ArrayList records = gson.fromJson(recordsArray, sqsMessageArray); - event.setRecords(records); - return event; - } -} \ No newline at end of file diff --git a/sample-apps/blank-java/template-mvn.yml b/sample-apps/blank-java/template-mvn.yml index d6cefd07..1b443cb7 100644 --- a/sample-apps/blank-java/template-mvn.yml +++ b/sample-apps/blank-java/template-mvn.yml @@ -7,14 +7,24 @@ Resources: Properties: CodeUri: target/blank-java-1.0-SNAPSHOT.jar Handler: example.Handler::handleRequest - Runtime: java8 + Runtime: java11 Description: Java function - MemorySize: 512 + MemorySize: 2048 Timeout: 10 # Function's execution role Policies: - AWSLambdaBasicExecutionRole - - AWSLambdaReadOnlyAccess + - AWSLambda_ReadOnlyAccess - AWSXrayWriteOnlyAccess - AWSLambdaVPCAccessExecutionRole Tracing: Active + Layers: + - !Ref libs + libs: + Type: AWS::Serverless::LayerVersion + Properties: + LayerName: blank-java-lib + Description: Dependencies for the blank-java sample app. + ContentUri: target/blank-java-1.0-SNAPSHOT.zip + CompatibleRuntimes: + - java11 \ No newline at end of file diff --git a/sample-apps/blank-java/template.yml b/sample-apps/blank-java/template.yml index fce3ade2..6e43d190 100644 --- a/sample-apps/blank-java/template.yml +++ b/sample-apps/blank-java/template.yml @@ -7,14 +7,14 @@ Resources: Properties: CodeUri: build/distributions/blank-java.zip Handler: example.Handler::handleRequest - Runtime: java8 + Runtime: java11 Description: Java function - MemorySize: 512 + MemorySize: 2048 Timeout: 10 # Function's execution role Policies: - AWSLambdaBasicExecutionRole - - AWSLambdaReadOnlyAccess + - AWSLambda_ReadOnlyAccess - AWSXrayWriteOnlyAccess - AWSLambdaVPCAccessExecutionRole Tracing: Active @@ -27,4 +27,4 @@ Resources: Description: Dependencies for the blank-java sample app. ContentUri: build/blank-java-lib.zip CompatibleRuntimes: - - java8 \ No newline at end of file + - java11 \ No newline at end of file diff --git a/sample-apps/blank-java/zip.xml b/sample-apps/blank-java/zip.xml new file mode 100644 index 00000000..14779c15 --- /dev/null +++ b/sample-apps/blank-java/zip.xml @@ -0,0 +1,19 @@ + + zip + false + + + zip + + + + ${project.build.directory}/classes/java + java/ + + example/ + + + + \ No newline at end of file diff --git a/sample-apps/blank-nodejs/2-build-layer.sh b/sample-apps/blank-nodejs/2-build-layer.sh index d30f3600..0385aba4 100755 --- a/sample-apps/blank-nodejs/2-build-layer.sh +++ b/sample-apps/blank-nodejs/2-build-layer.sh @@ -2,5 +2,5 @@ set -eo pipefail mkdir -p lib/nodejs rm -rf node_modules lib/nodejs/node_modules -npm install --production +npm install --omit=dev mv node_modules lib/nodejs/ \ No newline at end of file diff --git a/sample-apps/blank-nodejs/4-invoke.sh b/sample-apps/blank-nodejs/4-invoke.sh index 1ec3612c..b9cade74 100755 --- a/sample-apps/blank-nodejs/4-invoke.sh +++ b/sample-apps/blank-nodejs/4-invoke.sh @@ -3,7 +3,7 @@ set -eo pipefail FUNCTION=$(aws cloudformation describe-stack-resource --stack-name blank-nodejs --logical-resource-id function --query 'StackResourceDetail.PhysicalResourceId' --output text) while true; do - aws lambda invoke --function-name $FUNCTION --payload file://event.json out.json + aws lambda invoke --function-name $FUNCTION --payload fileb://event.json out.json cat out.json echo "" sleep 2 diff --git a/sample-apps/blank-nodejs/README.md b/sample-apps/blank-nodejs/README.md index b1b0854d..8f60acbc 100644 --- a/sample-apps/blank-nodejs/README.md +++ b/sample-apps/blank-nodejs/README.md @@ -21,9 +21,9 @@ Variants of this sample application are available for the following languages: Use the following instructions to deploy the sample application. For an in-depth look at its architecture and features, see [Blank Function Sample Application for AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/samples-blank-nodejs.html) in the developer guide. # Requirements -- [Node.js 10 with npm](https://nodejs.org/en/download/releases/) +- [Node.js 18 with npm](https://nodejs.org/en/download/releases/) - The Bash shell. For Linux and macOS, this is included by default. In Windows 10, you can install the [Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows-integrated version of Ubuntu and Bash. -- [The AWS CLI v1](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html). +- [The AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html) v1.17 or newer. # Setup Download or clone this repository. diff --git a/sample-apps/blank-nodejs/function/index.js b/sample-apps/blank-nodejs/function/index.js index eb471714..d4145bb6 100644 --- a/sample-apps/blank-nodejs/function/index.js +++ b/sample-apps/blank-nodejs/function/index.js @@ -1,26 +1,27 @@ -const AWSXRay = require('aws-xray-sdk-core') -const AWS = AWSXRay.captureAWS(require('aws-sdk')) +const AWSXRay = require('aws-xray-sdk-core'); +const { LambdaClient, GetAccountSettingsCommand } = require('@aws-sdk/client-lambda'); // Create client outside of handler to reuse -const lambda = new AWS.Lambda() +const lambda = AWSXRay.captureAWSv3Client(new LambdaClient()); // Handler exports.handler = async function(event, context) { - event.Records.forEach(record => { - console.log(record.body) - }) - console.log('## ENVIRONMENT VARIABLES: ' + serialize(process.env)) - console.log('## CONTEXT: ' + serialize(context)) - console.log('## EVENT: ' + serialize(event)) - - return getAccountSettings() -} + event.Records.forEach(record => { + console.log(record.body); + }); + + console.log('## ENVIRONMENT VARIABLES: ' + serialize(process.env)); + console.log('## CONTEXT: ' + serialize(context)); + console.log('## EVENT: ' + serialize(event)); + + return getAccountSettings(); +}; // Use SDK client -var getAccountSettings = function(){ - return lambda.getAccountSettings().promise() -} +var getAccountSettings = function() { + return lambda.send(new GetAccountSettingsCommand()); +}; var serialize = function(object) { - return JSON.stringify(object, null, 2) -} + return JSON.stringify(object, null, 2); +}; \ No newline at end of file diff --git a/sample-apps/blank-nodejs/package.json b/sample-apps/blank-nodejs/package.json index 9fa06adb..daf01e27 100644 --- a/sample-apps/blank-nodejs/package.json +++ b/sample-apps/blank-nodejs/package.json @@ -3,13 +3,13 @@ "version": "1.0.0", "private": true, "devDependencies": { - "aws-sdk": "2.631.0", - "jest": "25.4.0" + "jest": "29.7.0" }, "dependencies": { - "aws-xray-sdk-core": "1.1.2" + "@aws-sdk/client-lambda": "3.582.0", + "aws-xray-sdk-core": "3.6.0" }, "scripts": { "test": "jest" } -} +} \ No newline at end of file diff --git a/sample-apps/blank-nodejs/template.yml b/sample-apps/blank-nodejs/template.yml index 26659b40..a4c5b105 100644 --- a/sample-apps/blank-nodejs/template.yml +++ b/sample-apps/blank-nodejs/template.yml @@ -6,14 +6,14 @@ Resources: Type: AWS::Serverless::Function Properties: Handler: index.handler - Runtime: nodejs12.x + Runtime: nodejs20.x CodeUri: function/. Description: Call the AWS Lambda API Timeout: 10 # Function's execution role Policies: - AWSLambdaBasicExecutionRole - - AWSLambdaReadOnlyAccess + - AWSLambda_ReadOnlyAccess - AWSXrayWriteOnlyAccess Tracing: Active Layers: @@ -25,4 +25,4 @@ Resources: Description: Dependencies for the blank sample app. ContentUri: lib/. CompatibleRuntimes: - - nodejs12.x + - nodejs20.x \ No newline at end of file diff --git a/sample-apps/blank-powershell/3-invoke.sh b/sample-apps/blank-powershell/3-invoke.sh index 4aa193eb..06190ef1 100755 --- a/sample-apps/blank-powershell/3-invoke.sh +++ b/sample-apps/blank-powershell/3-invoke.sh @@ -3,7 +3,7 @@ set -eo pipefail FUNCTION=$(aws cloudformation describe-stack-resource --stack-name blank-powershell --logical-resource-id function --query 'StackResourceDetail.PhysicalResourceId' --output text) while true; do - aws lambda invoke --function-name $FUNCTION --payload file://event.json out.json + aws lambda invoke --function-name $FUNCTION --payload fileb://event.json out.json cat out.json echo "" sleep 2 diff --git a/sample-apps/blank-powershell/README.md b/sample-apps/blank-powershell/README.md index 03daf849..bcd58c97 100644 --- a/sample-apps/blank-powershell/README.md +++ b/sample-apps/blank-powershell/README.md @@ -15,7 +15,7 @@ Use the following instructions to deploy the sample application. - [.NET Core 3.1](https://www.microsoft.com/net/download) - [AWSLambdaPSCore module 2.0](https://www.powershellgallery.com/packages/AWSLambdaPSCore/2.0.0.0) - The Bash shell. For Linux and macOS, this is included by default. In Windows 10, you can install the [Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows-integrated version of Ubuntu and Bash. -- [The AWS CLI v1](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html). +- [The AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html) v1.17 or newer. # Setup Download or clone this repository. diff --git a/sample-apps/blank-powershell/template.yml b/sample-apps/blank-powershell/template.yml index 9b11775f..cbae139c 100644 --- a/sample-apps/blank-powershell/template.yml +++ b/sample-apps/blank-powershell/template.yml @@ -14,6 +14,6 @@ Resources: # Function's execution role Policies: - AWSLambdaBasicExecutionRole - - AWSLambdaReadOnlyAccess + - AWSLambda_ReadOnlyAccess - AWSXrayWriteOnlyAccess Tracing: Active diff --git a/sample-apps/blank-python/.idea/.gitignore b/sample-apps/blank-python/.idea/.gitignore new file mode 100644 index 00000000..13566b81 --- /dev/null +++ b/sample-apps/blank-python/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/sample-apps/blank-python/.idea/aws.xml b/sample-apps/blank-python/.idea/aws.xml new file mode 100644 index 00000000..2c4ea32b --- /dev/null +++ b/sample-apps/blank-python/.idea/aws.xml @@ -0,0 +1,17 @@ + + + + + + + \ No newline at end of file diff --git a/sample-apps/blank-python/.idea/blank-python.iml b/sample-apps/blank-python/.idea/blank-python.iml new file mode 100644 index 00000000..9b31378a --- /dev/null +++ b/sample-apps/blank-python/.idea/blank-python.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/sample-apps/blank-python/.idea/inspectionProfiles/profiles_settings.xml b/sample-apps/blank-python/.idea/inspectionProfiles/profiles_settings.xml new file mode 100644 index 00000000..105ce2da --- /dev/null +++ b/sample-apps/blank-python/.idea/inspectionProfiles/profiles_settings.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/sample-apps/blank-python/.idea/misc.xml b/sample-apps/blank-python/.idea/misc.xml new file mode 100644 index 00000000..d1e22ecb --- /dev/null +++ b/sample-apps/blank-python/.idea/misc.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/sample-apps/blank-python/.idea/modules.xml b/sample-apps/blank-python/.idea/modules.xml new file mode 100644 index 00000000..92f039cd --- /dev/null +++ b/sample-apps/blank-python/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/sample-apps/blank-python/.idea/vcs.xml b/sample-apps/blank-python/.idea/vcs.xml new file mode 100644 index 00000000..b2bdec2d --- /dev/null +++ b/sample-apps/blank-python/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/sample-apps/blank-python/2-build-layer.sh b/sample-apps/blank-python/2-build-layer.sh index 58f407b8..8f047d17 100755 --- a/sample-apps/blank-python/2-build-layer.sh +++ b/sample-apps/blank-python/2-build-layer.sh @@ -2,4 +2,4 @@ set -eo pipefail rm -rf package cd function -pip install --target ../package/python -r requirements.txt +pip3 install --target ../package/python -r requirements.txt diff --git a/sample-apps/blank-python/4-invoke.sh b/sample-apps/blank-python/4-invoke.sh index f6e429d5..c85e4944 100755 --- a/sample-apps/blank-python/4-invoke.sh +++ b/sample-apps/blank-python/4-invoke.sh @@ -3,7 +3,7 @@ set -eo pipefail FUNCTION=$(aws cloudformation describe-stack-resource --stack-name blank-python --logical-resource-id function --query 'StackResourceDetail.PhysicalResourceId' --output text) while true; do - aws lambda invoke --function-name $FUNCTION --payload file://event.json out.json + aws lambda invoke --function-name $FUNCTION --payload fileb://event.json out.json cat out.json echo "" sleep 2 diff --git a/sample-apps/blank-python/README.md b/sample-apps/blank-python/README.md index 19143adb..98d059b2 100644 --- a/sample-apps/blank-python/README.md +++ b/sample-apps/blank-python/README.md @@ -11,29 +11,35 @@ The project source includes function code and supporting resources: Use the following instructions to deploy the sample application. # Requirements -- [Python 3.7](https://www.python.org/downloads/) +- [Python 3.11](https://www.python.org/downloads/). Sample also works with Python 3.9. - The Bash shell. For Linux and macOS, this is included by default. In Windows 10, you can install the [Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows-integrated version of Ubuntu and Bash. -- [The AWS CLI v1](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html). +- [The AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html) v1.17 or newer. # Setup Download or clone this repository. - $ git clone https://github.com/awsdocs/aws-lambda-developer-guide.git - $ cd aws-lambda-developer-guide/sample-apps/blank-python + git clone https://github.com/awsdocs/aws-lambda-developer-guide.git + cd aws-lambda-developer-guide/sample-apps/blank-python To create a new bucket for deployment artifacts, run `1-create-bucket.sh`. - blank-python$ ./1-create-bucket.sh + ./1-create-bucket.sh + +Example output: + make_bucket: lambda-artifacts-a5e491dbb5b22e0d To build a Lambda layer that contains the function's runtime dependencies, run `2-build-layer.sh`. Packaging dependencies in a layer reduces the size of the deployment package that you upload when you modify your code. - blank-python$ ./2-build-layer.sh + ./2-build-layer.sh # Deploy To deploy the application, run `3-deploy.sh`. - blank-python$ ./3-deploy.sh + ./3-deploy.sh + +Example output: + Uploading to e678bc216e6a0d510d661ca9ae2fd941 9519118 / 9519118.0 (100.00%) Successfully packaged artifacts and wrote output template to file out.yml. Waiting for changeset to be created.. @@ -45,7 +51,10 @@ This script uses AWS CloudFormation to deploy the Lambda functions and an IAM ro # Test To invoke the function, run `4-invoke.sh`. - blank-python$ ./4-invoke.sh + ./4-invoke.sh + +Example output: + { "StatusCode": 200, "ExecutedVersion": "$LATEST" @@ -65,4 +74,4 @@ Choose a node in the main function graph. Then choose **View traces** to see a l # Cleanup To delete the application, run `5-cleanup.sh`. - blank-python$ ./5-cleanup.sh + ./5-cleanup.sh \ No newline at end of file diff --git a/sample-apps/blank-python/template.yml b/sample-apps/blank-python/template.yml index 7b14daf2..dc5024a6 100644 --- a/sample-apps/blank-python/template.yml +++ b/sample-apps/blank-python/template.yml @@ -6,14 +6,14 @@ Resources: Type: AWS::Serverless::Function Properties: Handler: lambda_function.lambda_handler - Runtime: python3.8 + Runtime: python3.11 CodeUri: function/. Description: Call the AWS Lambda API Timeout: 10 # Function's execution role Policies: - AWSLambdaBasicExecutionRole - - AWSLambdaReadOnlyAccess + - AWSLambda_ReadOnlyAccess - AWSXrayWriteOnlyAccess Tracing: Active Layers: @@ -25,4 +25,4 @@ Resources: Description: Dependencies for the blank-python sample app. ContentUri: package/. CompatibleRuntimes: - - python3.8 + - python3.11 \ No newline at end of file diff --git a/sample-apps/blank-ruby/4-invoke.sh b/sample-apps/blank-ruby/4-invoke.sh index 26c4ea96..fb9f725a 100755 --- a/sample-apps/blank-ruby/4-invoke.sh +++ b/sample-apps/blank-ruby/4-invoke.sh @@ -3,7 +3,7 @@ set -eo pipefail FUNCTION=$(aws cloudformation describe-stack-resource --stack-name blank-ruby --logical-resource-id function --query 'StackResourceDetail.PhysicalResourceId' --output text) while true; do - aws lambda invoke --function-name $FUNCTION --payload file://event.json out.json + aws lambda invoke --function-name $FUNCTION --payload fileb://event.json out.json cat out.json echo "" sleep 2 diff --git a/sample-apps/blank-ruby/README.md b/sample-apps/blank-ruby/README.md index 9e5df80d..49fcd9bc 100644 --- a/sample-apps/blank-ruby/README.md +++ b/sample-apps/blank-ruby/README.md @@ -13,7 +13,7 @@ Use the following instructions to deploy the sample application. # Requirements - [Ruby 2.5](https://www.ruby-lang.org/en/downloads/) - The Bash shell. For Linux and macOS, this is included by default. In Windows 10, you can install the [Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows-integrated version of Ubuntu and Bash. -- [The AWS CLI v1](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html). +- [The AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html) v1.17 or newer. # Setup Download or clone this repository. diff --git a/sample-apps/blank-ruby/template-2.7.yml b/sample-apps/blank-ruby/template-2.7.yml index 1a6410f1..39f2fe93 100644 --- a/sample-apps/blank-ruby/template-2.7.yml +++ b/sample-apps/blank-ruby/template-2.7.yml @@ -13,7 +13,7 @@ Resources: # Function's execution role Policies: - AWSLambdaBasicExecutionRole - - AWSLambdaReadOnlyAccess + - AWSLambda_ReadOnlyAccess - AWSXrayWriteOnlyAccess Tracing: Active Environment: diff --git a/sample-apps/blank-ruby/template.yml b/sample-apps/blank-ruby/template.yml index 00f841ad..9cd53133 100644 --- a/sample-apps/blank-ruby/template.yml +++ b/sample-apps/blank-ruby/template.yml @@ -13,7 +13,7 @@ Resources: # Function's execution role Policies: - AWSLambdaBasicExecutionRole - - AWSLambdaReadOnlyAccess + - AWSLambda_ReadOnlyAccess - AWSXrayWriteOnlyAccess Tracing: Active Environment: diff --git a/sample-apps/ec2-spot/README.md b/sample-apps/ec2-spot/README.md index 098c83a1..442e6a8d 100644 --- a/sample-apps/ec2-spot/README.md +++ b/sample-apps/ec2-spot/README.md @@ -11,9 +11,9 @@ The project source includes function code and supporting resources: Use the following instructions to deploy the sample application. For more information on the application's architecture and implementation, see [Managing Spot Instance Requests](https://docs.aws.amazon.com/lambda/latest/dg/services-ec2-tutorial.html) in the developer guide. # Requirements -- [.NET Core SDK 2.1](https://nodejs.org/en/download/releases/) +- [.NET Core SDK 2.1](https://dotnet.microsoft.com/download/dotnet-core/2.1) - The Bash shell. For Linux and macOS, this is included by default. In Windows 10, you can install the [Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows-integrated version of Ubuntu and Bash. -- [The AWS CLI v1](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html). +- [The AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html) v1.17 or newer. # Setup Download or clone this repository. diff --git a/sample-apps/error-processor/1-create-bucket.sh b/sample-apps/error-processor/1-create-bucket.sh deleted file mode 100755 index 64a5f749..00000000 --- a/sample-apps/error-processor/1-create-bucket.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/bash -BUCKET_ID=$(dd if=/dev/random bs=8 count=1 2>/dev/null | od -An -tx1 | tr -d ' \t\n') -BUCKET_NAME=lambda-artifacts-$BUCKET_ID -echo $BUCKET_NAME > bucket-name.txt -aws s3 mb s3://$BUCKET_NAME diff --git a/sample-apps/error-processor/2-build-layer.sh b/sample-apps/error-processor/2-build-layer.sh deleted file mode 100755 index caf7b985..00000000 --- a/sample-apps/error-processor/2-build-layer.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/bash -set -eo pipefail -mkdir -p lib/nodejs -rm -rf lib/nodejs/node_modules -npm install -mv node_modules lib/nodejs/ \ No newline at end of file diff --git a/sample-apps/error-processor/3-deploy.sh b/sample-apps/error-processor/3-deploy.sh deleted file mode 100755 index 80e798cd..00000000 --- a/sample-apps/error-processor/3-deploy.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/bash -ARTIFACT_BUCKET=$(cat bucket-name.txt) -aws cloudformation package --template-file template.yml --s3-bucket $ARTIFACT_BUCKET --output-template-file out.yml -aws cloudformation deploy --template-file out.yml --stack-name error-processor --capabilities CAPABILITY_NAMED_IAM diff --git a/sample-apps/error-processor/4-invoke.sh b/sample-apps/error-processor/4-invoke.sh deleted file mode 100755 index 1c323d73..00000000 --- a/sample-apps/error-processor/4-invoke.sh +++ /dev/null @@ -1,21 +0,0 @@ -#!/bin/bash -ERROR_FUNCTION=$(aws cloudformation describe-stack-resource --stack-name error-processor --logical-resource-id randomerror --query 'StackResourceDetail.PhysicalResourceId' --output text) - -while true; do - if [ $1 ] - then - case $1 in - async) - aws lambda invoke --function-name $ERROR_FUNCTION --payload file://event.json --invocation-type Event out.json - ;; - *) - echo -n "Unknown argument" - ;; - esac - else - aws lambda invoke --function-name $ERROR_FUNCTION --payload file://event.json out.json - fi - cat out.json - echo "" - sleep 2 -done \ No newline at end of file diff --git a/sample-apps/error-processor/5-cleanup.sh b/sample-apps/error-processor/5-cleanup.sh deleted file mode 100755 index 3cdc8707..00000000 --- a/sample-apps/error-processor/5-cleanup.sh +++ /dev/null @@ -1,48 +0,0 @@ -#!/bin/bash -set -eo pipefail -STACK=error-processor -if [[ $# -eq 1 ]] ; then - STACK=$1 - echo "Deleting stack $STACK" -fi -APP_BUCKET=$(aws cloudformation describe-stack-resource --stack-name $STACK --logical-resource-id bucket --query 'StackResourceDetail.PhysicalResourceId' --output text) -FUNCTION=$(aws cloudformation describe-stack-resource --stack-name $STACK --logical-resource-id function --query 'StackResourceDetail.PhysicalResourceId' --output text) -aws cloudformation delete-stack --stack-name $STACK -echo "Deleted $STACK stack." - -if [ -f bucket-name.txt ]; then - ARTIFACT_BUCKET=$(cat bucket-name.txt) - if [[ ! $ARTIFACT_BUCKET =~ lambda-artifacts-[a-z0-9]{16} ]] ; then - echo "Bucket was not created by this application. Skipping." - else - while true; do - read -p "Delete deployment artifacts and bucket ($ARTIFACT_BUCKET)? (y/n)" response - case $response in - [Yy]* ) aws s3 rb --force s3://$ARTIFACT_BUCKET; rm bucket-name.txt; break;; - [Nn]* ) break;; - * ) echo "Response must start with y or n.";; - esac - done - fi -fi - -while true; do - read -p "Delete function log group (/aws/lambda/$FUNCTION)? (y/n)" response - case $response in - [Yy]* ) aws logs delete-log-group --log-group-name /aws/lambda/$FUNCTION; break;; - [Nn]* ) break;; - * ) echo "Response must start with y or n.";; - esac -done - -while true; do - read -p "Delete application bucket ($APP_BUCKET)?" response - case $response in - [Yy]* ) aws s3 rb --force s3://$APP_BUCKET; break;; - [Nn]* ) break;; - * ) echo "Response must start with y or n.";; - esac -done - -rm -f out.yml out.json -rm -rf processor/node_modules random-error/node_modules processor/package-lock.json random-error/package-lock.json \ No newline at end of file diff --git a/sample-apps/error-processor/README.md b/sample-apps/error-processor/README.md deleted file mode 100644 index 7ae0de8f..00000000 --- a/sample-apps/error-processor/README.md +++ /dev/null @@ -1,124 +0,0 @@ -# Error processing with CloudWatch Logs and X-Ray - -This sample application triggers a Lambda function when CloudWatch Logs detects the word ERROR in a log stream. The function downloads the full log stream and the X-Ray trace for the request that caused the error. It stores both in an Amazon S3 bucket. - -![Architecture](/sample-apps/error-processor/images/sample-errorprocessor.png) - -The project source includes function code and supporting resources: - -- `processor` - A Node.js function that retrieves logs and traces, and stores them in Amazon S3. -- `random-error` - A Node.js function that generates errors at random. -- `template.yml` - An AWS CloudFormation template that creates an application with the processor and random-error functions. -- `1-createbucket.sh`, `2-deploy.sh`, etc. - Shell scripts that use the AWS CLI to deploy and manage the application. - -Use the following instructions to deploy the sample application. For more information on the application's architecture and implementation, see [Error Processor Sample Application for AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/sample-errorprocessor.html) in the developer guide. - -# Requirements -- [Node.js 10 with npm](https://nodejs.org/en/download/releases/) -- The Bash shell. For Linux and macOS, this is included by default. In Windows 10, you can install the [Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows-integrated version of Ubuntu and Bash. -- [The AWS CLI v1](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html). - -# Setup -Download or clone this repository. - - $ git clone https://github.com/awsdocs/aws-lambda-developer-guide.git - $ cd aws-lambda-developer-guide/sample-apps/error-processor - -To create a new bucket for deployment artifacts, run `1-create-bucket.sh`. - - error-processor$ ./1-create-bucket.sh - make_bucket: lambda-artifacts-a5e491dbb5b22e0d - -To build a Lambda layer that contains the function's runtime dependencies, run `2-build-layer.sh`. Packaging dependencies in a layer reduces the size of the deployment package that you upload when you modify your code. - - blank-ruby$ ./2-build-layer.sh - -# Deploy -To deploy the application, run `3-deploy.sh`. - - error-processor$ ./3-deploy.sh - added 16 packages from 18 contributors and audited 18 packages in 1.979s - found 0 vulnerabilities - added 17 packages from 19 contributors and audited 19 packages in 1.782s - Uploading to e678bc216e6a0d510d661ca9ae2fd941 2737254 / 2737254.0 (100.00%) - Successfully packaged artifacts and wrote output template to file out.yml. - Waiting for changeset to be created.. - Waiting for stack create/update to complete - Successfully created/updated stack - error-processor - -This script uses AWS CloudFormation to deploy the Lambda functions, an IAM role, and a CloudWatch Logs subscription that triggers the processor function. If the AWS CloudFormation stack that contains the resources already exists, the script updates it with any changes to the template or function code. - -# Test -To generate logs and errors, invoke the random error function. - - error-processor$ ./4-invoke.sh - { - "StatusCode": 200, - "FunctionError": "Unhandled", - "ExecutedVersion": "$LATEST" - } - {"errorType":"function.DoublesRolledError","errorMessage":"Doubles rolled: 10 & 10","trace":["function.DoublesRolledError: Doubles rolled: 10 & 10"," at Runtime.myFunction [as handler] (/var/task/index.js:36:17)"," at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"]} - { - "StatusCode": 200, - "ExecutedVersion": "$LATEST" - } - {"errorType":"function.DoublesRolledError","errorMessage":"Doubles rolled: 2 & 2","trace":["function.DoublesRolledError: Doubles rolled: 2 & 2"," at Runtime.myFunction [as handler] (/var/task/index.js:36:17)"," at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"],"depth":8} - { - "StatusCode": 200, - "ExecutedVersion": "$LATEST" - } - {"errorType":"function.MaxDepthError","errorMessage":"Maximum depth reached: 9","trace":["function.MaxDepthError: Maximum depth reached: 9"," at Runtime.myFunction [as handler] (/var/task/index.js:30:17)"," at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"],"depth":9} - -Let the script invoke the function a few times and then press `CRTL+C` to exit. - -This function generates errors for a configurable percentage of invocations. When an error does not occur, it invokes itself recursively until one does. The event (`event.json`) provides a base error rate and maximum recursion depth. - - { - "max-depth": 9, - "current-depth": 0, - "error-rate": 0.07 - } - -The application uses AWS X-Ray to trace requests. Open the [X-Ray console](https://console.aws.amazon.com/xray/home#/service-map) to view the service map. The following service map shows the random error function generating errors for some requests. It also shows the processor function calling X-Ray, CloudWatch Logs, and Amazon S3. - -![Service Map](/sample-apps/error-processor/images/errorprocessor-servicemap.png) - -Choose a node in the main function graph. Then choose **View traces** to see a list of traces. Choose any trace to view a timeline that breaks down the work done by the function. The following example shows a trace for the processor function, which is invoked by CloudWatch Logs for each error. - -![Trace - Processor](/sample-apps/error-processor/images/errorprocessor-trace.png) - -Traces for the random error function include all recursive calls. The following example shows a request that resulted in 3 invocations. The third invocation resulted in an error that was relayed back through the other two (successful) invocations to the requester. - -![Trace - Random Error](/sample-apps/error-processor/images/errorprocessor-trace-randomerror.png) - -Click on the error icon next to the function segment for the final invocation to see details about the exception. - -![Trace - Exception](/sample-apps/error-processor/images/errorprocessor-exception.png) - -Finally, view the logs and traces that the function stores in Amazon S3. - -*To view the output* -1. Open the [applications page](https://console.aws.amazon.com/lambda/home#/applications) in the Lambda console. -2. Choose **error-processor**. - - ![Application](/sample-apps/error-processor/images/errorprocessor-application.png) - -3. Choose **bucket**. -4. Choose **errors**. -5. Choose a request ID. -6. For each file, check the box next to the filename and then choose **Download**. - -# Configure the random error function - -With the default configuration, the function runs up to 9 times before returning an error. When invoked continuously with the AWS CLI, it maintains a concurrency of 9, with approximately 100 invocations per minute, including when the function invokes itself. The effective error rate is close to 14%. - -To generate a larger, more varied set of data, lower the error rate and increase the maximum depth. The following example shows a service map for the application running with an error rate of 0.5% and a maximum depth of 500. - -![Service Map](/sample-apps/error-processor/images/errorprocessor-servicemap-traffic.png) - -Lambda records traces for the first request each second and 5% of additional requests. - -# Cleanup -To delete the application, run the cleanup script. - - error-processor$ ./5-cleanup.sh diff --git a/sample-apps/error-processor/event.json b/sample-apps/error-processor/event.json deleted file mode 100644 index 49fe97ae..00000000 --- a/sample-apps/error-processor/event.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "max-depth": 10, - "current-depth": 0, - "error-rate": 0.05 -} \ No newline at end of file diff --git a/sample-apps/error-processor/images/errorprocessor-application.png b/sample-apps/error-processor/images/errorprocessor-application.png deleted file mode 100644 index 317d1334..00000000 Binary files a/sample-apps/error-processor/images/errorprocessor-application.png and /dev/null differ diff --git a/sample-apps/error-processor/images/errorprocessor-exception.png b/sample-apps/error-processor/images/errorprocessor-exception.png deleted file mode 100644 index 99ea009f..00000000 Binary files a/sample-apps/error-processor/images/errorprocessor-exception.png and /dev/null differ diff --git a/sample-apps/error-processor/images/errorprocessor-servicemap-traffic.png b/sample-apps/error-processor/images/errorprocessor-servicemap-traffic.png deleted file mode 100644 index 83f20929..00000000 Binary files a/sample-apps/error-processor/images/errorprocessor-servicemap-traffic.png and /dev/null differ diff --git a/sample-apps/error-processor/images/errorprocessor-servicemap.png b/sample-apps/error-processor/images/errorprocessor-servicemap.png deleted file mode 100644 index 890cf570..00000000 Binary files a/sample-apps/error-processor/images/errorprocessor-servicemap.png and /dev/null differ diff --git a/sample-apps/error-processor/images/errorprocessor-trace-randomerror.png b/sample-apps/error-processor/images/errorprocessor-trace-randomerror.png deleted file mode 100644 index e0a1c0d7..00000000 Binary files a/sample-apps/error-processor/images/errorprocessor-trace-randomerror.png and /dev/null differ diff --git a/sample-apps/error-processor/images/errorprocessor-trace.png b/sample-apps/error-processor/images/errorprocessor-trace.png deleted file mode 100644 index 85f642e1..00000000 Binary files a/sample-apps/error-processor/images/errorprocessor-trace.png and /dev/null differ diff --git a/sample-apps/error-processor/images/sample-errorprocessor.png b/sample-apps/error-processor/images/sample-errorprocessor.png deleted file mode 100644 index f4cf1909..00000000 Binary files a/sample-apps/error-processor/images/sample-errorprocessor.png and /dev/null differ diff --git a/sample-apps/error-processor/package.json b/sample-apps/error-processor/package.json deleted file mode 100644 index bd2bfa96..00000000 --- a/sample-apps/error-processor/package.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "error-processor", - "version": "1.0.0", - "private": true, - "devDependencies": { - "aws-sdk": "2.631.0" - }, - "dependencies": { - "aws-xray-sdk-core": "1.1.2", - "chance": "1.0.16" - } -} diff --git a/sample-apps/error-processor/processor/index.js b/sample-apps/error-processor/processor/index.js deleted file mode 100644 index 8894ab27..00000000 --- a/sample-apps/error-processor/processor/index.js +++ /dev/null @@ -1,107 +0,0 @@ -var zlib = require('zlib') -var AWSXRay = require('aws-xray-sdk-core') -var AWS = AWSXRay.captureAWS(require('aws-sdk')) - -var cloudwatchlogs = new AWS.CloudWatchLogs() -var s3 = new AWS.S3() -var xray = new AWS.XRay() - -const bucket = process.env.bucket - -var putObject = function(data, filename, context){ - var s3params = { - Body: JSON.stringify(data, null, 2), - Bucket: bucket, - Key: filename - } - s3.putObject(s3params, function(err, data) { - if (err) console.log(err, err.stack) - else console.log(data) - }) -} - -var getLogStream = function(context, group, stream){ - // download log stream - var params = { - logGroupName: group, - logStreamName: stream, - } - console.log("GROUP: " + group) - cloudwatchlogs.getLogEvents(params, function(err, data) { - if (err) console.log(err, err.stack) - else { - var filename = "errors/" + context.requestid + "/log-events.json" - putObject(data, filename, context) - } - }) -} - -var getTrace = function(context){ - var startTime = new Date - var endTime = new Date - startTime.setHours(endTime.getHours() - 1) - var xrayparams = { - EndTime: endTime, - StartTime: startTime, - FilterExpression: 'annotation.request_id="' + context.requestid + '"', - NextToken: context.NextToken - } - console.log(xrayparams) - xray.getTraceSummaries(xrayparams, function(err, data) { - if (err) console.log(err, err.stack) - else if (data.TraceSummaries[0] == null && data.NextToken != null) { - context.NextToken = data.NextToken - getTrace(context) - } else if (data.TraceSummaries[0] == null) { - console.log("Trace not found.") - } - else { - console.log(data) - var traceid = data.TraceSummaries[0].Id - console.log(traceid) - var params = { - TraceIds: [ traceid ] - } - xray.batchGetTraces(params, function(err, data) { - if (err) console.log(err, err.stack) - else { - console.log(data) - var s3params = { - Body: JSON.stringify(data, null, 2), - Bucket: bucket, - Key: "errors/" + context.requestid + "/request-trace.json" - } - s3.putObject(s3params, function(err, data) { - if (err) console.log(err, err.stack) - else console.log(data) - }) - } - }) - } - }) -} - -exports.handler = function(event, context) { - console.log("Event: " + JSON.stringify(event, null, 2)) - var payload = new Buffer(event.awslogs.data, 'base64') - zlib.gunzip(payload, function(e, decodedEvent) { - if (e) { - context.fail(e) - } else { - console.log("Decoded event: " + decodedEvent) - decodedEvent = JSON.parse(decodedEvent.toString('ascii')) - try { - context.requestid = decodedEvent.logEvents[0].message.match(/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/)[0] - } catch (TypeError){ - console.log("Request ID not found. Error is outside of traced request loop.") - return - } - console.log(context.requestid) - // download log stream - setTimeout(function(){getLogStream(context, decodedEvent.logGroup, decodedEvent.logStream)}, 10000) - // download trace - setTimeout(function(){getTrace(context)}, 20000) - //context.succeed() - } - }) -} \ No newline at end of file diff --git a/sample-apps/error-processor/random-error/index.js b/sample-apps/error-processor/random-error/index.js deleted file mode 100644 index 7728d1ba..00000000 --- a/sample-apps/error-processor/random-error/index.js +++ /dev/null @@ -1,53 +0,0 @@ -const AWSXRay = require('aws-xray-sdk-core') -const aws = AWSXRay.captureAWS(require('aws-sdk')) - -const Chance = require('chance') -const lambda = new aws.Lambda() - -var myFunction = async function(event, context) { - var chance = new Chance() - var name = chance.first() - var roll1 = chance.integer({ min: 1, max: 1/event["error-rate"] }) - var roll2 = chance.integer({ min: 1, max: 1/event["error-rate"] }) - - var guid = chance.guid() - console.log("## EVENT: " + JSON.stringify(event, null, 2)) - console.log("GUID: " + guid) - console.log("Name: " + name) - console.log("Roll 1: " + roll1) - console.log("Roll 2: " + roll2) - - AWSXRay.captureFunc('annotations', function(subsegment){ - subsegment.addAnnotation('name', name) - subsegment.addAnnotation('roll1', roll1) - subsegment.addAnnotation('roll2', roll2) - subsegment.addAnnotation('request_id', context.awsRequestId) - }) - - - event["current-depth"] += 1 - if (event["max-depth"] == event["current-depth"]) { - var error = new Error("Maximum depth reached: " + event["max-depth"]) - error.name = "function.MaxDepthError" - console.log("ERROR") - throw error - } - if (roll1 == roll2) { - var error = new Error(`Doubles rolled: ${roll1} & ${roll2}`) - error.name= "function.DoublesRolledError" - console.log("ERROR") - throw error - } - - var invokeResponse = await lambda.invoke({ FunctionName: context.functionName, Payload: JSON.stringify(event)}).promise() - var response = JSON.parse(invokeResponse.Payload) - if ( !response.depth ){ - response.depth = 2 - } - else { - response.depth +=1 - } - return response -} - -exports.handler = myFunction \ No newline at end of file diff --git a/sample-apps/error-processor/template.yml b/sample-apps/error-processor/template.yml deleted file mode 100644 index 7705f567..00000000 --- a/sample-apps/error-processor/template.yml +++ /dev/null @@ -1,128 +0,0 @@ -AWSTemplateFormatVersion: '2010-09-09' -Transform: 'AWS::Serverless-2016-10-31' -Description: An AWS Lambda application that uses Amazon CloudWatch Logs, AWS X-Ray, and AWS CloudFormation custom resources. -Globals: - Function: - Runtime: nodejs12.x - Handler: index.handler - Tracing: Active - Layers: - - !Ref libs -Resources: - bucket: - Type: AWS::S3::Bucket - DeletionPolicy: Retain - role: - Type: AWS::IAM::Role - Properties: - AssumeRolePolicyDocument: - Version: "2012-10-17" - Statement: - - - Effect: Allow - Principal: - Service: - - lambda.amazonaws.com - Action: - - sts:AssumeRole - ManagedPolicyArns: - - arn:aws:iam::aws:policy/AWSXrayFullAccess - - arn:aws:iam::aws:policy/AmazonS3FullAccess - - arn:aws:iam::aws:policy/CloudWatchLogsFullAccess - - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole - - arn:aws:iam::aws:policy/service-role/AWSLambdaRole - Path: /service-role/ - processor: - Type: AWS::Serverless::Function - Properties: - CodeUri: processor/. - Description: Retrieve logs and trace for errors. - Timeout: 40 - Role: !GetAtt role.Arn - Environment: - Variables: - bucket: !Ref bucket - libs: - Type: AWS::Serverless::LayerVersion - Properties: - LayerName: error-processor-lib - Description: Dependencies for the error-processor sample app. - ContentUri: lib/. - CompatibleRuntimes: - - nodejs12.x - randomerror: - Type: AWS::Serverless::Function - Properties: - CodeUri: random-error/. - Description: Generate errors. - Timeout: 600 - Role: !GetAtt role.Arn - primer: - Type: AWS::Serverless::Function - Properties: - InlineCode: | - var aws = require('aws-sdk') - var response = require('cfn-response') - exports.handler = async function(event, context) { - console.log("REQUEST RECEIVED:\n" + JSON.stringify(event)) - // For Delete requests, immediately send a SUCCESS response. - if (event.RequestType == "Delete") { - return await response.send(event, context, "SUCCESS") - } - var responseStatus = "FAILED" - var responseData = {} - var functionName1 = event.ResourceProperties.FunctionName1 - var functionName2 = event.ResourceProperties.FunctionName2 - var functionName3 = event.ResourceProperties.FunctionName3 - var logGroup1 = "/aws/lambda/" + functionName1 - var logGroup2 = "/aws/lambda/" + functionName2 - var logGroup3 = "/aws/lambda/" + functionName3 - var lambda = new aws.Lambda() - var logs = new aws.CloudWatchLogs() - try { - // Invoke other functions and wait for log groups to populate - await Promise.all([ - lambda.invoke({ FunctionName: functionName2 }).promise(), - lambda.invoke({ FunctionName: functionName3 }).promise(), - new Promise(resolve => setTimeout(resolve, 10000)) - ]) - // Set log retention on all log groups - await Promise.all([ - logs.putRetentionPolicy({logGroupName: logGroup1, retentionInDays: 3 }).promise(), - logs.putRetentionPolicy({logGroupName: logGroup2, retentionInDays: 3 }).promise(), - logs.putRetentionPolicy({logGroupName: logGroup3, retentionInDays: 3 }).promise() - ])} catch(err) { - responseData = {Error: "SDK call failed"} - console.log(responseData.Error + ":\n", err) - return await response.send(event, context, responseStatus, responseData) - } - responseStatus = "SUCCESS" - return await response.send(event, context, responseStatus, responseData) - } - Description: Invoke a function to create a log stream. - Role: !GetAtt role.Arn - Timeout: 30 - primerinvoke: - Type: AWS::CloudFormation::CustomResource - Version: "1.0" - Properties: - ServiceToken: !GetAtt primer.Arn - FunctionName1: !Ref primer - FunctionName2: !Ref randomerror - FunctionName3: !Ref processor - subscription: - Type: AWS::Logs::SubscriptionFilter - DependsOn: cloudwatchlogspermission - Properties: - LogGroupName: !Join [ "/", [ "/aws/lambda", !Ref randomerror ] ] - FilterPattern: ERROR - DestinationArn: !GetAtt processor.Arn - cloudwatchlogspermission: - Type: AWS::Lambda::Permission - # Wait for randomerror to be invoked to ensure that the log stream exists. - DependsOn: primerinvoke - Properties: - FunctionName: !GetAtt processor.Arn - Action: lambda:InvokeFunction - Principal: !Join [ ".", [ "logs", !Ref "AWS::Region", "amazonaws.com" ] ] - SourceAccount: !Ref AWS::AccountId diff --git a/sample-apps/example-csharp/ExampleCS/src/ExampleCS/ExampleCS.csproj b/sample-apps/example-csharp/ExampleCS/src/ExampleCS/ExampleCS.csproj new file mode 100644 index 00000000..a57cd339 --- /dev/null +++ b/sample-apps/example-csharp/ExampleCS/src/ExampleCS/ExampleCS.csproj @@ -0,0 +1,18 @@ + + + net8.0 + enable + enable + true + Lambda + + true + + true + + + + + + + \ No newline at end of file diff --git a/sample-apps/example-csharp/ExampleCS/src/ExampleCS/Function.cs b/sample-apps/example-csharp/ExampleCS/src/ExampleCS/Function.cs new file mode 100644 index 00000000..b1142dba --- /dev/null +++ b/sample-apps/example-csharp/ExampleCS/src/ExampleCS/Function.cs @@ -0,0 +1,68 @@ +using System; +using System.Text; +using System.Threading.Tasks; +using Amazon.Lambda.Core; +using Amazon.S3; +using Amazon.S3.Model; + +// Assembly attribute to enable Lambda function logging +[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] + +namespace ExampleLambda; + +public class Order +{ + public string OrderId { get; set; } = string.Empty; + public double Amount { get; set; } + public string Item { get; set; } = string.Empty; +} + +public class OrderHandler +{ + private static readonly AmazonS3Client s3Client = new(); + + public async Task HandleRequest(Order order, ILambdaContext context) + { + try + { + string? bucketName = Environment.GetEnvironmentVariable("RECEIPT_BUCKET"); + if (string.IsNullOrWhiteSpace(bucketName)) + { + throw new ArgumentException("RECEIPT_BUCKET environment variable is not set"); + } + + string receiptContent = $"OrderID: {order.OrderId}\nAmount: ${order.Amount:F2}\nItem: {order.Item}"; + string key = $"receipts/{order.OrderId}.txt"; + + await UploadReceiptToS3(bucketName, key, receiptContent); + + context.Logger.LogInformation($"Successfully processed order {order.OrderId} and stored receipt in S3 bucket {bucketName}"); + return "Success"; + } + catch (Exception ex) + { + context.Logger.LogError($"Failed to process order: {ex.Message}"); + throw; + } + } + + private async Task UploadReceiptToS3(string bucketName, string key, string receiptContent) + { + try + { + var putRequest = new PutObjectRequest + { + BucketName = bucketName, + Key = key, + ContentBody = receiptContent, + ContentType = "text/plain" + }; + + await s3Client.PutObjectAsync(putRequest); + } + catch (AmazonS3Exception ex) + { + throw new Exception($"Failed to upload receipt to S3: {ex.Message}", ex); + } + } +} diff --git a/sample-apps/example-csharp/ExampleCS/src/ExampleCS/Readme.md b/sample-apps/example-csharp/ExampleCS/src/ExampleCS/Readme.md new file mode 100644 index 00000000..422393ec --- /dev/null +++ b/sample-apps/example-csharp/ExampleCS/src/ExampleCS/Readme.md @@ -0,0 +1,49 @@ +# AWS Lambda Empty Function Project + +This starter project consists of: +* Function.cs - class file containing a class with a single function handler method +* aws-lambda-tools-defaults.json - default argument settings for use with Visual Studio and command line deployment tools for AWS + +You may also have a test project depending on the options selected. + +The generated function handler is a simple method accepting a string argument that returns the uppercase equivalent of the input string. Replace the body of this method, and parameters, to suit your needs. + +## Here are some steps to follow from Visual Studio: + +To deploy your function to AWS Lambda, right click the project in Solution Explorer and select *Publish to AWS Lambda*. + +To view your deployed function open its Function View window by double-clicking the function name shown beneath the AWS Lambda node in the AWS Explorer tree. + +To perform testing against your deployed function use the Test Invoke tab in the opened Function View window. + +To configure event sources for your deployed function, for example to have your function invoked when an object is created in an Amazon S3 bucket, use the Event Sources tab in the opened Function View window. + +To update the runtime configuration of your deployed function use the Configuration tab in the opened Function View window. + +To view execution logs of invocations of your function use the Logs tab in the opened Function View window. + +## Here are some steps to follow to get started from the command line: + +Once you have edited your template and code you can deploy your application using the [Amazon.Lambda.Tools Global Tool](https://github.com/aws/aws-extensions-for-dotnet-cli#aws-lambda-amazonlambdatools) from the command line. + +Install Amazon.Lambda.Tools Global Tools if not already installed. +``` + dotnet tool install -g Amazon.Lambda.Tools +``` + +If already installed check if new version is available. +``` + dotnet tool update -g Amazon.Lambda.Tools +``` + +Execute unit tests +``` + cd "ExampleCS/test/ExampleCS.Tests" + dotnet test +``` + +Deploy function to AWS Lambda +``` + cd "ExampleCS/src/ExampleCS" + dotnet lambda deploy-function +``` diff --git a/sample-apps/example-csharp/ExampleCS/src/ExampleCS/aws-lambda-tools-defaults.json b/sample-apps/example-csharp/ExampleCS/src/ExampleCS/aws-lambda-tools-defaults.json new file mode 100644 index 00000000..a9757798 --- /dev/null +++ b/sample-apps/example-csharp/ExampleCS/src/ExampleCS/aws-lambda-tools-defaults.json @@ -0,0 +1,16 @@ +{ + "Information": [ + "This file provides default values for the deployment wizard inside Visual Studio and the AWS Lambda commands added to the .NET Core CLI.", + "To learn more about the Lambda commands with the .NET Core CLI execute the following command at the command line in the project root directory.", + "dotnet lambda help", + "All the command line options for the Lambda command can be specified in this file." + ], + "profile": "default", + "region": "us-east-1", + "configuration": "Release", + "function-architecture": "x86_64", + "function-runtime": "dotnet8", + "function-memory-size": 512, + "function-timeout": 30, + "function-handler": "ExampleCS::ExampleLambda.OrderHandler::HandleRequest" +} \ No newline at end of file diff --git a/sample-apps/example-csharp/ExampleCS/test/ExampleCS.Tests/ExampleCS.Tests.csproj b/sample-apps/example-csharp/ExampleCS/test/ExampleCS.Tests/ExampleCS.Tests.csproj new file mode 100644 index 00000000..4aa7182a --- /dev/null +++ b/sample-apps/example-csharp/ExampleCS/test/ExampleCS.Tests/ExampleCS.Tests.csproj @@ -0,0 +1,18 @@ + + + net8.0 + enable + enable + true + + + + + + + + + + + + \ No newline at end of file diff --git a/sample-apps/example-csharp/ExampleCS/test/ExampleCS.Tests/FunctionTest.cs b/sample-apps/example-csharp/ExampleCS/test/ExampleCS.Tests/FunctionTest.cs new file mode 100644 index 00000000..07640759 --- /dev/null +++ b/sample-apps/example-csharp/ExampleCS/test/ExampleCS.Tests/FunctionTest.cs @@ -0,0 +1,20 @@ +using Xunit; +using Amazon.Lambda.Core; +using Amazon.Lambda.TestUtilities; + +namespace ExampleCS.Tests; + +public class FunctionTest +{ + [Fact] + public void TestToUpperFunction() + { + + // Invoke the lambda function and confirm the string was upper cased. + var function = new Function(); + var context = new TestLambdaContext(); + var upperCase = function.FunctionHandler("hello world", context); + + Assert.Equal("HELLO WORLD", upperCase); + } +} diff --git a/sample-apps/example-go/function/event.json b/sample-apps/example-go/function/event.json new file mode 100644 index 00000000..ed49258a --- /dev/null +++ b/sample-apps/example-go/function/event.json @@ -0,0 +1,5 @@ +{ + "order_id": "12345", + "amount": 199.99, + "item": "Wireless Headphones" +} diff --git a/sample-apps/example-go/function/go.mod b/sample-apps/example-go/function/go.mod new file mode 100644 index 00000000..2fa563fd --- /dev/null +++ b/sample-apps/example-go/function/go.mod @@ -0,0 +1,28 @@ +module example-go + +go 1.22.6 + +require ( + github.com/aws/aws-lambda-go v1.47.0 + github.com/aws/aws-sdk-go-v2/config v1.27.27 + github.com/aws/aws-sdk-go-v2/service/s3 v1.58.3 +) + +require ( + github.com/aws/aws-sdk-go-v2 v1.30.3 // indirect + github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.3 // indirect + github.com/aws/aws-sdk-go-v2/credentials v1.17.27 // indirect + github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.11 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.15 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.15 // indirect + github.com/aws/aws-sdk-go-v2/internal/ini v1.8.0 // indirect + github.com/aws/aws-sdk-go-v2/internal/v4a v1.3.15 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.11.3 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.3.17 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.17 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.17.15 // indirect + github.com/aws/aws-sdk-go-v2/service/sso v1.22.4 // indirect + github.com/aws/aws-sdk-go-v2/service/ssooidc v1.26.4 // indirect + github.com/aws/aws-sdk-go-v2/service/sts v1.30.3 // indirect + github.com/aws/smithy-go v1.20.3 // indirect +) diff --git a/sample-apps/example-go/function/go.sum b/sample-apps/example-go/function/go.sum new file mode 100644 index 00000000..67b0f34f --- /dev/null +++ b/sample-apps/example-go/function/go.sum @@ -0,0 +1,46 @@ +github.com/aws/aws-lambda-go v1.47.0 h1:0H8s0vumYx/YKs4sE7YM0ktwL2eWse+kfopsRI1sXVI= +github.com/aws/aws-lambda-go v1.47.0/go.mod h1:dpMpZgvWx5vuQJfBt0zqBha60q7Dd7RfgJv23DymV8A= +github.com/aws/aws-sdk-go-v2 v1.30.3 h1:jUeBtG0Ih+ZIFH0F4UkmL9w3cSpaMv9tYYDbzILP8dY= +github.com/aws/aws-sdk-go-v2 v1.30.3/go.mod h1:nIQjQVp5sfpQcTc9mPSr1B0PaWK5ByX9MOoDadSN4lc= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.3 h1:tW1/Rkad38LA15X4UQtjXZXNKsCgkshC3EbmcUmghTg= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.3/go.mod h1:UbnqO+zjqk3uIt9yCACHJ9IVNhyhOCnYk8yA19SAWrM= +github.com/aws/aws-sdk-go-v2/config v1.27.27 h1:HdqgGt1OAP0HkEDDShEl0oSYa9ZZBSOmKpdpsDMdO90= +github.com/aws/aws-sdk-go-v2/config v1.27.27/go.mod h1:MVYamCg76dFNINkZFu4n4RjDixhVr51HLj4ErWzrVwg= +github.com/aws/aws-sdk-go-v2/credentials v1.17.27 h1:2raNba6gr2IfA0eqqiP2XiQ0UVOpGPgDSi0I9iAP+UI= +github.com/aws/aws-sdk-go-v2/credentials v1.17.27/go.mod h1:gniiwbGahQByxan6YjQUMcW4Aov6bLC3m+evgcoN4r4= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.11 h1:KreluoV8FZDEtI6Co2xuNk/UqI9iwMrOx/87PBNIKqw= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.11/go.mod h1:SeSUYBLsMYFoRvHE0Tjvn7kbxaUhl75CJi1sbfhMxkU= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.15 h1:SoNJ4RlFEQEbtDcCEt+QG56MY4fm4W8rYirAmq+/DdU= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.15/go.mod h1:U9ke74k1n2bf+RIgoX1SXFed1HLs51OgUSs+Ph0KJP8= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.15 h1:C6WHdGnTDIYETAm5iErQUiVNsclNx9qbJVPIt03B6bI= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.15/go.mod h1:ZQLZqhcu+JhSrA9/NXRm8SkDvsycE+JkV3WGY41e+IM= +github.com/aws/aws-sdk-go-v2/internal/ini v1.8.0 h1:hT8rVHwugYE2lEfdFE0QWVo81lF7jMrYJVDWI+f+VxU= +github.com/aws/aws-sdk-go-v2/internal/ini v1.8.0/go.mod h1:8tu/lYfQfFe6IGnaOdrpVgEL2IrrDOf6/m9RQum4NkY= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.3.15 h1:Z5r7SycxmSllHYmaAZPpmN8GviDrSGhMS6bldqtXZPw= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.3.15/go.mod h1:CetW7bDE00QoGEmPUoZuRog07SGVAUVW6LFpNP0YfIg= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.11.3 h1:dT3MqvGhSoaIhRseqw2I0yH81l7wiR2vjs57O51EAm8= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.11.3/go.mod h1:GlAeCkHwugxdHaueRr4nhPuY+WW+gR8UjlcqzPr1SPI= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.3.17 h1:YPYe6ZmvUfDDDELqEKtAd6bo8zxhkm+XEFEzQisqUIE= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.3.17/go.mod h1:oBtcnYua/CgzCWYN7NZ5j7PotFDaFSUjCYVTtfyn7vw= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.17 h1:HGErhhrxZlQ044RiM+WdoZxp0p+EGM62y3L6pwA4olE= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.17/go.mod h1:RkZEx4l0EHYDJpWppMJ3nD9wZJAa8/0lq9aVC+r2UII= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.17.15 h1:246A4lSTXWJw/rmlQI+TT2OcqeDMKBdyjEQrafMaQdA= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.17.15/go.mod h1:haVfg3761/WF7YPuJOER2MP0k4UAXyHaLclKXB6usDg= +github.com/aws/aws-sdk-go-v2/service/s3 v1.58.3 h1:hT8ZAZRIfqBqHbzKTII+CIiY8G2oC9OpLedkZ51DWl8= +github.com/aws/aws-sdk-go-v2/service/s3 v1.58.3/go.mod h1:Lcxzg5rojyVPU/0eFwLtcyTaek/6Mtic5B1gJo7e/zE= +github.com/aws/aws-sdk-go-v2/service/sso v1.22.4 h1:BXx0ZIxvrJdSgSvKTZ+yRBeSqqgPM89VPlulEcl37tM= +github.com/aws/aws-sdk-go-v2/service/sso v1.22.4/go.mod h1:ooyCOXjvJEsUw7x+ZDHeISPMhtwI3ZCB7ggFMcFfWLU= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.26.4 h1:yiwVzJW2ZxZTurVbYWA7QOrAaCYQR72t0wrSBfoesUE= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.26.4/go.mod h1:0oxfLkpz3rQ/CHlx5hB7H69YUpFiI1tql6Q6Ne+1bCw= +github.com/aws/aws-sdk-go-v2/service/sts v1.30.3 h1:ZsDKRLXGWHk8WdtyYMoGNO7bTudrvuKpDKgMVRlepGE= +github.com/aws/aws-sdk-go-v2/service/sts v1.30.3/go.mod h1:zwySh8fpFyXp9yOr/KVzxOl8SRqgf/IDw5aUt9UKFcQ= +github.com/aws/smithy-go v1.20.3 h1:ryHwveWzPV5BIof6fyDvor6V3iUL7nTfiTKXHiW05nE= +github.com/aws/smithy-go v1.20.3/go.mod h1:krry+ya/rV9RDcV/Q16kpu6ypI4K2czasz0NC3qS14E= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.7.2 h1:4jaiDzPyXQvSd7D0EjG45355tLlV3VOECpq10pLC+8s= +github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/sample-apps/example-go/function/main.go b/sample-apps/example-go/function/main.go new file mode 100644 index 00000000..f9f9bb16 --- /dev/null +++ b/sample-apps/example-go/function/main.go @@ -0,0 +1,80 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "log" + "os" + "strings" + + "github.com/aws/aws-lambda-go/lambda" + "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/service/s3" +) + +type Order struct { + OrderID string `json:"order_id"` + Amount float64 `json:"amount"` + Item string `json:"item"` +} + +var ( + s3Client *s3.Client +) + +func init() { + // Initialize the S3 client outside of the handler, during the init phase + cfg, err := config.LoadDefaultConfig(context.TODO()) + if err != nil { + log.Fatalf("unable to load SDK config, %v", err) + } + + s3Client = s3.NewFromConfig(cfg) +} + +func uploadReceiptToS3(ctx context.Context, bucketName, key, receiptContent string) error { + _, err := s3Client.PutObject(ctx, &s3.PutObjectInput{ + Bucket: &bucketName, + Key: &key, + Body: strings.NewReader(receiptContent), + }) + if err != nil { + log.Printf("Failed to upload receipt to S3: %v", err) + return err + } + return nil +} + +func handleRequest(ctx context.Context, event json.RawMessage) error { + // Parse the input event + var order Order + if err := json.Unmarshal(event, &order); err != nil { + log.Printf("Failed to unmarshal event: %v", err) + return err + } + + // Access environment variables + bucketName := os.Getenv("RECEIPT_BUCKET") + if bucketName == "" { + log.Printf("RECEIPT_BUCKET environment variable is not set") + return fmt.Errorf("missing required environment variable RECEIPT_BUCKET") + } + + // Create the receipt content and key destination + receiptContent := fmt.Sprintf("OrderID: %s\nAmount: $%.2f\nItem: %s", + order.OrderID, order.Amount, order.Item) + key := "receipts/" + order.OrderID + ".txt" + + // Upload the receipt to S3 using the helper method + if err := uploadReceiptToS3(ctx, bucketName, key, receiptContent); err != nil { + return err + } + + log.Printf("Successfully processed order %s and stored receipt in S3 bucket %s", order.OrderID, bucketName) + return nil +} + +func main() { + lambda.Start(handleRequest) +} diff --git a/sample-apps/example-java/function/build.gradle b/sample-apps/example-java/function/build.gradle new file mode 100644 index 00000000..ab6730c9 --- /dev/null +++ b/sample-apps/example-java/function/build.gradle @@ -0,0 +1,28 @@ +plugins { + id 'java' +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'com.amazonaws:aws-lambda-java-core:1.2.3' + implementation 'software.amazon.awssdk:s3:2.28.29' + implementation 'org.slf4j:slf4j-nop:2.0.16' +} + +task buildZip(type: Zip) { + from compileJava + from processResources + into('lib') { + from configurations.runtimeClasspath + } +} + +java { + sourceCompatibility = JavaVersion.VERSION_21 + targetCompatibility = JavaVersion.VERSION_21 +} + +build.dependsOn buildZip diff --git a/sample-apps/example-java/function/pom.xml b/sample-apps/example-java/function/pom.xml new file mode 100644 index 00000000..72c3b301 --- /dev/null +++ b/sample-apps/example-java/function/pom.xml @@ -0,0 +1,73 @@ + + 4.0.0 + com.example + example-java + jar + 1.0-SNAPSHOT + example-java-function + + UTF-8 + 21 + 21 + + + + com.amazonaws + aws-lambda-java-core + 1.2.3 + + + software.amazon.awssdk + s3 + 2.28.29 + + + org.slf4j + slf4j-nop + 2.0.16 + + + + + + + maven-surefire-plugin + 3.5.2 + + + org.apache.maven.plugins + maven-shade-plugin + 3.4.1 + + false + + + *:* + + META-INF/* + META-INF/versions/** + + + + + + + package + + shade + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.13.0 + + 21 + + + + + \ No newline at end of file diff --git a/sample-apps/example-java/function/src/main/java/example/OrderHandler.java b/sample-apps/example-java/function/src/main/java/example/OrderHandler.java new file mode 100644 index 00000000..df50eef0 --- /dev/null +++ b/sample-apps/example-java/function/src/main/java/example/OrderHandler.java @@ -0,0 +1,64 @@ +package example; + +import com.amazonaws.services.lambda.runtime.Context; +import com.amazonaws.services.lambda.runtime.RequestHandler; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.S3Exception; + +import java.nio.charset.StandardCharsets; + +/** + * Lambda handler for processing orders and storing receipts in S3. + */ +public class OrderHandler implements RequestHandler { + + private static final S3Client S3_CLIENT = S3Client.builder().build(); + + /** + * Record to model the input event. + */ + public record Order(String orderId, double amount, String item) {} + + @Override + public String handleRequest(Order event, Context context) { + try { + // Access environment variables + String bucketName = System.getenv("RECEIPT_BUCKET"); + if (bucketName == null || bucketName.isEmpty()) { + throw new IllegalArgumentException("RECEIPT_BUCKET environment variable is not set"); + } + + // Create the receipt content and key destination + String receiptContent = String.format("OrderID: %s\nAmount: $%.2f\nItem: %s", + event.orderId(), event.amount(), event.item()); + String key = "receipts/" + event.orderId() + ".txt"; + + // Upload the receipt to S3 + uploadReceiptToS3(bucketName, key, receiptContent); + + context.getLogger().log("Successfully processed order " + event.orderId() + + " and stored receipt in S3 bucket " + bucketName); + return "Success"; + + } catch (Exception e) { + context.getLogger().log("Failed to process order: " + e.getMessage()); + throw new RuntimeException(e); + } + } + + private void uploadReceiptToS3(String bucketName, String key, String receiptContent) { + try { + PutObjectRequest putObjectRequest = PutObjectRequest.builder() + .bucket(bucketName) + .key(key) + .build(); + + // Convert the receipt content to bytes and upload to S3 + S3_CLIENT.putObject(putObjectRequest, RequestBody.fromBytes(receiptContent.getBytes(StandardCharsets.UTF_8))); + } catch (S3Exception e) { + throw new RuntimeException("Failed to upload receipt to S3: " + e.awsErrorDetails().errorMessage(), e); + } + } +} diff --git a/sample-apps/file-processing-python/lambda_function.py b/sample-apps/file-processing-python/lambda_function.py new file mode 100644 index 00000000..58b5bb2a --- /dev/null +++ b/sample-apps/file-processing-python/lambda_function.py @@ -0,0 +1,46 @@ +from pypdf import PdfReader, PdfWriter +import uuid +import os +from urllib.parse import unquote_plus +import boto3 + +# Create the S3 client to download and upload objects from S3 +s3_client = boto3.client('s3') + +def lambda_handler(event, context): + # Iterate over the S3 event object and get the key for all uploaded files + for record in event['Records']: + bucket = record['s3']['bucket']['name'] + key = unquote_plus(record['s3']['object']['key']) # Decode the S3 object key to remove any URL-encoded characters + download_path = f'/tmp/{uuid.uuid4()}.pdf' # Create a path in the Lambda tmp directory to save the file to + upload_path = f'/tmp/converted-{uuid.uuid4()}.pdf' # Create another path to save the encrypted file to + + # If the file is a PDF, encrypt it and upload it to the destination S3 bucket + if key.lower().endswith('.pdf'): + s3_client.download_file(bucket, key, download_path) + encrypt_pdf(download_path, upload_path) + encrypted_key = add_encrypted_suffix(key) + s3_client.upload_file(upload_path, f'{bucket}-encrypted', encrypted_key) + +# Define the function to encrypt the PDF file with a password +def encrypt_pdf(file_path, encrypted_file_path): + reader = PdfReader(file_path) + writer = PdfWriter() + + for page in reader.pages: + writer.add_page(page) + + # Add a password to the new PDF + # In this example, the password is hardcoded. + # In a production application, don't hardcode passwords or other sensitive information. + # We recommend you use AWS Secrets Manager to securely store passwords. + writer.encrypt("my-secret-password") + + # Save the new PDF to a file + with open(encrypted_file_path, "wb") as file: + writer.write(file) + +# Define a function to add a suffix to the original filename after encryption +def add_encrypted_suffix(original_key): + filename, extension = original_key.rsplit('.', 1) + return f'{filename}_encrypted.{extension}' \ No newline at end of file diff --git a/sample-apps/file-processing-python/pytest.ini b/sample-apps/file-processing-python/pytest.ini new file mode 100644 index 00000000..715b6262 --- /dev/null +++ b/sample-apps/file-processing-python/pytest.ini @@ -0,0 +1,3 @@ +[pytest] +markers = + order: specify test execution order \ No newline at end of file diff --git a/sample-apps/file-processing-python/requirements.txt b/sample-apps/file-processing-python/requirements.txt new file mode 100644 index 00000000..e7c65556 --- /dev/null +++ b/sample-apps/file-processing-python/requirements.txt @@ -0,0 +1,2 @@ +boto3 +pypdf \ No newline at end of file diff --git a/sample-apps/file-processing-python/template.yaml b/sample-apps/file-processing-python/template.yaml new file mode 100644 index 00000000..0f40e195 --- /dev/null +++ b/sample-apps/file-processing-python/template.yaml @@ -0,0 +1,34 @@ +AWSTemplateFormatVersion: '2010-09-09' +Transform: AWS::Serverless-2016-10-31 + +Resources: + EncryptPDFFunction: + Type: AWS::Serverless::Function + Properties: + FunctionName: EncryptPDF + Architectures: [x86_64] + CodeUri: ./ + Handler: lambda_function.lambda_handler + Runtime: python3.12 + Timeout: 15 + MemorySize: 256 + LoggingConfig: + LogFormat: JSON + Policies: + - AmazonS3FullAccess + Events: + S3Event: + Type: S3 + Properties: + Bucket: !Ref PDFSourceBucket + Events: s3:ObjectCreated:* + + PDFSourceBucket: + Type: AWS::S3::Bucket + Properties: + BucketName: EXAMPLE-BUCKET + + EncryptedPDFBucket: + Type: AWS::S3::Bucket + Properties: + BucketName: EXAMPLE-BUCKET-encrypted \ No newline at end of file diff --git a/sample-apps/file-processing-python/test_pdf_encrypt.py b/sample-apps/file-processing-python/test_pdf_encrypt.py new file mode 100644 index 00000000..a0da8210 --- /dev/null +++ b/sample-apps/file-processing-python/test_pdf_encrypt.py @@ -0,0 +1,104 @@ +import boto3 +import json +import pytest +import time +import os + +@pytest.fixture +def lambda_client(): + return boto3.client('lambda') + +@pytest.fixture +def s3_client(): + return boto3.client('s3') + +@pytest.fixture +def logs_client(): + return boto3.client('logs') + +@pytest.fixture(scope='session') +def cleanup(): + # Create a new S3 client for cleanup + s3_client = boto3.client('s3') + + yield + # Cleanup code will be executed after all tests have finished + + # Delete test.pdf from the source bucket + source_bucket = 'EXAMPLE-BUCKET' + source_file_key = 'test.pdf' + s3_client.delete_object(Bucket=source_bucket, Key=source_file_key) + print(f"\nDeleted {source_file_key} from {source_bucket}") + + # Delete test_encrypted.pdf from the destination bucket + destination_bucket = 'EXAMPLE-BUCKET-encrypted' + destination_file_key = 'test_encrypted.pdf' + s3_client.delete_object(Bucket=destination_bucket, Key=destination_file_key) + print(f"Deleted {destination_file_key} from {destination_bucket}") + + +@pytest.mark.order(1) +def test_source_bucket_available(s3_client): + s3_bucket_name = 'EXAMPLE-BUCKET' + file_name = 'test.pdf' + file_path = os.path.join(os.path.dirname(__file__), file_name) + + file_uploaded = False + try: + s3_client.upload_file(file_path, s3_bucket_name, file_name) + file_uploaded = True + except: + print("Error: couldn't upload file") + + assert file_uploaded, "Could not upload file to S3 bucket" + + + +@pytest.mark.order(2) +def test_lambda_invoked(logs_client): + + # Wait for a few seconds to make sure the logs are available + time.sleep(5) + + # Get the latest log stream for the specified log group + log_streams = logs_client.describe_log_streams( + logGroupName='/aws/lambda/EncryptPDF', + orderBy='LastEventTime', + descending=True, + limit=1 + ) + + latest_log_stream_name = log_streams['logStreams'][0]['logStreamName'] + + # Retrieve the log events from the latest log stream + log_events = logs_client.get_log_events( + logGroupName='/aws/lambda/EncryptPDF', + logStreamName=latest_log_stream_name + ) + + success_found = False + for event in log_events['events']: + message = json.loads(event['message']) + status = message.get('record', {}).get('status') + if status == 'success': + success_found = True + break + + assert success_found, "Lambda function execution did not report 'success' status in logs." + +@pytest.mark.order(3) +def test_encrypted_file_in_bucket(s3_client): + # Specify the destination S3 bucket and the expected converted file key + destination_bucket = 'EXAMPLE-BUCKET-encrypted' + converted_file_key = 'test_encrypted.pdf' + + try: + # Attempt to retrieve the metadata of the converted file from the destination S3 bucket + s3_client.head_object(Bucket=destination_bucket, Key=converted_file_key) + except s3_client.exceptions.ClientError as e: + # If the file is not found, the test will fail + pytest.fail(f"Converted file '{converted_file_key}' not found in the destination bucket: {str(e)}") + +def test_cleanup(cleanup): + # This test uses the cleanup fixture and will be executed last + pass \ No newline at end of file diff --git a/sample-apps/java-basic/3-invoke.sh b/sample-apps/java-basic/3-invoke.sh index 35ee7663..ca4af147 100755 --- a/sample-apps/java-basic/3-invoke.sh +++ b/sample-apps/java-basic/3-invoke.sh @@ -30,7 +30,7 @@ while true; do then aws lambda invoke --function-name $FUNCTION --payload $PAYLOAD out.json else - aws lambda invoke --function-name $FUNCTION --payload file://event.json out.json + aws lambda invoke --function-name $FUNCTION --payload fileb://event.json out.json fi cat out.json echo "" diff --git a/sample-apps/java-basic/README.md b/sample-apps/java-basic/README.md index 8885600c..ad958afe 100644 --- a/sample-apps/java-basic/README.md +++ b/sample-apps/java-basic/README.md @@ -16,7 +16,7 @@ Use the following instructions to deploy the sample application. - [Java 8 runtime environment (SE JRE)](https://www.oracle.com/java/technologies/javase-downloads.html) - [Gradle 5](https://gradle.org/releases/) or [Maven 3](https://maven.apache.org/docs/history.html) - The Bash shell. For Linux and macOS, this is included by default. In Windows 10, you can install the [Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows-integrated version of Ubuntu and Bash. -- [The AWS CLI v1](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html). +- [The AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html) v1.17 or newer. # Setup Download or clone this repository. @@ -87,7 +87,7 @@ To use a different handler, change the value of the Handler setting in the appli CodeUri: build/distributions/java-basic.zip Handler: example.HandlerList -Deploy the change, and then use the invoke script to test the new configuration. For handlers, that don't take a JSON object as input, pass the type (`string`, `int` or `list`) as an argument to the invoke script. +Deploy the change, and then use the invoke script to test the new configuration. For handlers, that don't take a JSON object as input, pass the type (`string`, `int`, `list`, or `divide`) as an argument to the invoke script. ./3-invoke.sh list { diff --git a/sample-apps/java-basic/build.gradle b/sample-apps/java-basic/build.gradle index 1f976009..9b5f19ed 100644 --- a/sample-apps/java-basic/build.gradle +++ b/sample-apps/java-basic/build.gradle @@ -7,13 +7,11 @@ repositories { } dependencies { - implementation 'com.amazonaws:aws-lambda-java-core:1.2.0' - implementation 'com.google.code.gson:gson:2.8.6' - testImplementation 'org.apache.logging.log4j:log4j-api:2.13.0' - testImplementation 'org.apache.logging.log4j:log4j-core:2.13.0' - testImplementation 'org.apache.logging.log4j:log4j-slf4j18-impl:2.13.0' - testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0' - testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.6.0' + implementation 'com.amazonaws:aws-lambda-java-core:1.2.1' + implementation 'org.slf4j:slf4j-nop:2.0.6' + implementation 'com.fasterxml.jackson.core:jackson-databind:2.17.0' + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.2' + testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.2' } test { @@ -29,8 +27,9 @@ task buildZip(type: Zip) { } java { - sourceCompatibility = JavaVersion.VERSION_1_8 - targetCompatibility = JavaVersion.VERSION_1_8 + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } } build.dependsOn buildZip diff --git a/sample-apps/java-basic/pom.xml b/sample-apps/java-basic/pom.xml index 90cdc064..ccff43f1 100644 --- a/sample-apps/java-basic/pom.xml +++ b/sample-apps/java-basic/pom.xml @@ -8,50 +8,39 @@ java-basic-function UTF-8 - 1.8 - 1.8 + 21 + ${java.version} + ${java.version} + ${java.version} com.amazonaws aws-lambda-java-core - 1.2.0 + 1.2.1 - com.google.code.gson - gson - 2.8.6 + org.slf4j + slf4j-nop + 2.0.6 - org.apache.logging.log4j - log4j-api - 2.13.0 - test - - - org.apache.logging.log4j - log4j-core - 2.13.0 - test - + com.fasterxml.jackson.core + jackson-databind + 2.17.0 + - org.apache.logging.log4j - log4j-slf4j18-impl - 2.13.0 - test - - org.junit.jupiter junit-jupiter-api - 5.6.0 + 5.8.2 test - - + + org.junit.jupiter junit-jupiter-engine - 5.6.0 + 5.8.2 test - + @@ -66,6 +55,17 @@ 3.2.2 false + + + *:* + + module-info.class + META-INF/* + META-INF/versions/** + META-INF/services/** + + + @@ -81,8 +81,8 @@ maven-compiler-plugin 3.8.1 - 1.8 - 1.8 + 11 + 11 diff --git a/sample-apps/java-basic/src/main/java/example/Handler.java b/sample-apps/java-basic/src/main/java/example/Handler.java index 5d8d9ab2..5bb2090e 100644 --- a/sample-apps/java-basic/src/main/java/example/Handler.java +++ b/sample-apps/java-basic/src/main/java/example/Handler.java @@ -1,28 +1,19 @@ package example; import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.LambdaLogger; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import com.amazonaws.services.lambda.runtime.RequestHandler; import java.util.Map; // Handler value: example.Handler -public class Handler implements RequestHandler, String>{ - Gson gson = new GsonBuilder().setPrettyPrinting().create(); +public class Handler implements RequestHandler, Void>{ + @Override - public String handleRequest(Map event, Context context) + public Void handleRequest(Map event, Context context) { LambdaLogger logger = context.getLogger(); - String response = new String("200 OK"); - // log execution details - logger.log("ENVIRONMENT VARIABLES: " + gson.toJson(System.getenv())); - logger.log("CONTEXT: " + gson.toJson(context)); - // process event - logger.log("EVENT: " + gson.toJson(event)); - logger.log("EVENT TYPE: " + event.getClass().toString()); - return response; + logger.log("EVENT TYPE: " + event.getClass()); + return null; } } \ No newline at end of file diff --git a/sample-apps/java-basic/src/main/java/example/HandlerDivide.java b/sample-apps/java-basic/src/main/java/example/HandlerDivide.java index c6c6c840..1498b612 100644 --- a/sample-apps/java-basic/src/main/java/example/HandlerDivide.java +++ b/sample-apps/java-basic/src/main/java/example/HandlerDivide.java @@ -1,30 +1,28 @@ package example; import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.LambdaLogger; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import com.amazonaws.services.lambda.runtime.RequestHandler; import java.util.List; // Handler value: example.HandlerDivide public class HandlerDivide implements RequestHandler, Integer>{ - Gson gson = new GsonBuilder().setPrettyPrinting().create(); + /* + * Takes a list of two integers and divides them. + */ @Override public Integer handleRequest(List event, Context context) { LambdaLogger logger = context.getLogger(); - // process event if ( event.size() != 2 ) { throw new InputLengthException("Input must be an array that contains 2 numbers."); } int numerator = event.get(0); int denominator = event.get(1); - logger.log("EVENT: " + gson.toJson(event)); - logger.log("EVENT TYPE: " + event.getClass().toString()); + logger.log("EVENT: Numerator is " + event.get(0).toString() + + "; Denominator is " + event.get(1).toString()); return numerator/denominator; } } \ No newline at end of file diff --git a/sample-apps/java-basic/src/main/java/example/HandlerInteger.java b/sample-apps/java-basic/src/main/java/example/HandlerInteger.java index 89d2a33b..8cac870f 100644 --- a/sample-apps/java-basic/src/main/java/example/HandlerInteger.java +++ b/sample-apps/java-basic/src/main/java/example/HandlerInteger.java @@ -1,23 +1,20 @@ package example; import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.LambdaLogger; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import com.amazonaws.services.lambda.runtime.RequestHandler; // Handler value: example.HandlerInteger public class HandlerInteger implements RequestHandler{ - Gson gson = new GsonBuilder().setPrettyPrinting().create(); + @Override + /* + * Takes an Integer as input, adds 1, and returns it. + */ public Integer handleRequest(Integer event, Context context) { LambdaLogger logger = context.getLogger(); - // process event - logger.log("EVENT: " + gson.toJson(event)); logger.log("EVENT TYPE: " + event.getClass().toString()); - // return amount of time remaining before timeout - return context.getRemainingTimeInMillis(); + return event + 1; } } \ No newline at end of file diff --git a/sample-apps/java-basic/src/main/java/example/HandlerList.java b/sample-apps/java-basic/src/main/java/example/HandlerList.java index e286272d..d5b05884 100644 --- a/sample-apps/java-basic/src/main/java/example/HandlerList.java +++ b/sample-apps/java-basic/src/main/java/example/HandlerList.java @@ -1,24 +1,22 @@ package example; import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.LambdaLogger; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import com.amazonaws.services.lambda.runtime.RequestHandler; import java.util.List; // Handler value: example.HandlerList public class HandlerList implements RequestHandler, Integer>{ - Gson gson = new GsonBuilder().setPrettyPrinting().create(); + @Override + /* + * Takes a list of Integers and returns its sum. + */ public Integer handleRequest(List event, Context context) { LambdaLogger logger = context.getLogger(); - // process event - logger.log("EVENT: " + gson.toJson(event)); logger.log("EVENT TYPE: " + event.getClass().toString()); - return context.getRemainingTimeInMillis() ; + return event.stream().mapToInt(Integer::intValue).sum(); } } \ No newline at end of file diff --git a/sample-apps/java-basic/src/main/java/example/HandlerStream.java b/sample-apps/java-basic/src/main/java/example/HandlerStream.java index 4b100168..7460cb5a 100644 --- a/sample-apps/java-basic/src/main/java/example/HandlerStream.java +++ b/sample-apps/java-basic/src/main/java/example/HandlerStream.java @@ -1,53 +1,39 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: MIT-0 + package example; import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.LambdaLogger; import com.amazonaws.services.lambda.runtime.RequestStreamHandler; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonSyntaxException; - -import java.util.HashMap; -import java.io.InputStream; import java.io.IOException; +import java.io.InputStream; import java.io.OutputStream; -import java.io.InputStreamReader; -import java.io.BufferedReader; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.io.BufferedWriter; -import java.nio.charset.Charset; -import java.lang.IllegalStateException; - -// Handler value: example.HandlerStream +import java.util.List; + public class HandlerStream implements RequestStreamHandler { - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - @Override - public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException - { - LambdaLogger logger = context.getLogger(); - BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("US-ASCII"))); - PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream, Charset.forName("US-ASCII")))); - try - { - HashMap event = gson.fromJson(reader, HashMap.class); - logger.log("STREAM TYPE: " + inputStream.getClass().toString()); - logger.log("EVENT TYPE: " + event.getClass().toString()); - writer.write(gson.toJson(event)); - if (writer.checkError()) - { - logger.log("WARNING: Writer encountered an error."); - } - } - catch (IllegalStateException | JsonSyntaxException exception) - { - logger.log(exception.toString()); + + private static final ObjectMapper objectMapper = new ObjectMapper(); + + @Override + public void handleRequest(InputStream input, OutputStream output, Context context) throws IOException { + Order order = objectMapper.readValue(input, Order.class); + + processOrder(order); + OrderAccepted orderAccepted = new OrderAccepted(order.orderId); + + objectMapper.writeValue(output, orderAccepted); } - finally - { - reader.close(); - writer.close(); + + private void processOrder(Order order) { + // business logic } - } + + public record Order(@JsonProperty("orderId") String orderId, @JsonProperty("items") List items) { } + + public record Item(@JsonProperty("name") String name, @JsonProperty("quantity") Integer quantity) { } + + public record OrderAccepted(@JsonProperty("orderId") String orderId) { } } \ No newline at end of file diff --git a/sample-apps/java-basic/src/main/java/example/HandlerString.java b/sample-apps/java-basic/src/main/java/example/HandlerString.java index eb2aafc9..029bbc9c 100644 --- a/sample-apps/java-basic/src/main/java/example/HandlerString.java +++ b/sample-apps/java-basic/src/main/java/example/HandlerString.java @@ -1,22 +1,20 @@ package example; import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.LambdaLogger; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import com.amazonaws.services.lambda.runtime.RequestHandler; // Handler value: example.HandlerString -public class HandlerString implements RequestHandler{ - Gson gson = new GsonBuilder().setPrettyPrinting().create(); +public class HandlerString implements RequestHandler{ + @Override - public Integer handleRequest(String event, Context context) + /* + * Takes a String as input, and converts all characters to lowercase. + */ + public String handleRequest(String event, Context context) { LambdaLogger logger = context.getLogger(); - // process event - logger.log("EVENT: " + gson.toJson(event)); logger.log("EVENT TYPE: " + event.getClass().toString()); - return context.getRemainingTimeInMillis() ; + return event.toLowerCase(); } } \ No newline at end of file diff --git a/sample-apps/java-basic/src/main/java/example/HandlerWeatherData.java b/sample-apps/java-basic/src/main/java/example/HandlerWeatherData.java index d3ebbc4d..06f1ca7a 100644 --- a/sample-apps/java-basic/src/main/java/example/HandlerWeatherData.java +++ b/sample-apps/java-basic/src/main/java/example/HandlerWeatherData.java @@ -1,24 +1,27 @@ package example; import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.LambdaLogger; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import java.util.Map; +import com.amazonaws.services.lambda.runtime.RequestHandler; // Handler value: example.HandlerWeatherData public class HandlerWeatherData implements RequestHandler{ - Gson gson = new GsonBuilder().setPrettyPrinting().create(); + @Override + /* + * Takes in a WeatherData event object and updates its attributes with dummy values. + * Returns the updated WeatherData object. + */ public WeatherData handleRequest(WeatherData event, Context context) { LambdaLogger logger = context.getLogger(); - // process event - logger.log("EVENT: " + gson.toJson(event)); logger.log("EVENT TYPE: " + event.getClass().toString()); + + event.setHumidityPct(50.5); + event.setPressureHPa(1005); + event.setWindKmh(28); + // Assumes temperature of event is already set + event.setTemperatureK(event.getTemperatureK() + 2); return event; } } \ No newline at end of file diff --git a/sample-apps/java-basic/src/main/java/example/InputLengthException.java b/sample-apps/java-basic/src/main/java/example/InputLengthException.java index 6dea47c2..ee62bb9c 100644 --- a/sample-apps/java-basic/src/main/java/example/InputLengthException.java +++ b/sample-apps/java-basic/src/main/java/example/InputLengthException.java @@ -6,4 +6,4 @@ public class InputLengthException extends RuntimeException { public InputLengthException(String errorMessage) { super(errorMessage); } -} \ No newline at end of file +} diff --git a/sample-apps/java-basic/src/test/java/example/InvokeTest.java b/sample-apps/java-basic/src/test/java/example/InvokeTest.java index c274aa6c..d04eb402 100644 --- a/sample-apps/java-basic/src/test/java/example/InvokeTest.java +++ b/sample-apps/java-basic/src/test/java/example/InvokeTest.java @@ -1,30 +1,105 @@ package example; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.List; -import java.util.ArrayList; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; import java.util.HashMap; +import java.util.List; class InvokeTest { private static final Logger logger = LoggerFactory.getLogger(InvokeTest.class); @Test - void invokeTest() { - logger.info("Invoke TEST"); - HashMap event = new HashMap(); + void testHandler() { + logger.info("Invoke TEST - Handler"); + var event = new HashMap(); Context context = new TestContext(); Handler handler = new Handler(); - String result = handler.handleRequest(event, context); - assertTrue(result.contains("200 OK")); + assertNull(handler.handleRequest(event, context)); } + @Test + void testHandlerDivide() { + logger.info("Invoke TEST - HandlerDivide"); + var event = List.of(20, 5); + Context context = new TestContext(); + HandlerDivide handler = new HandlerDivide(); + assertEquals(4, handler.handleRequest(event, context)); + } + + @Test + void testHandlerInteger() { + logger.info("Invoke TEST - HandlerInteger"); + Integer event = 1; + Context context = new TestContext(); + HandlerInteger handler = new HandlerInteger(); + assertEquals(2, handler.handleRequest(event, context)); + } + + @Test + void testHandlerList() { + logger.info("Invoke TEST - HandlerList"); + var event = List.of(1, 2, 3, 4); + Context context = new TestContext(); + HandlerList handler = new HandlerList(); + assertEquals(10, handler.handleRequest(event, context)); + } + + @Test + public void testHandlerStream() throws IOException { + HandlerStream orderProcessor = new HandlerStream(); + String input = """ + { + "orderId": "123", + "items": [ + { + "name": "widgets", + "quantity": 10 + } + ] + } + """; + Context context = null; + ByteArrayInputStream inputStream = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)); + OutputStream outputStream = new ByteArrayOutputStream(); + + orderProcessor.handleRequest(inputStream, outputStream, context); + + assertEquals("{\"orderId\":\"123\"}", outputStream.toString()); + } + + @Test + void testHandlerString() { + logger.info("Invoke TEST - HandlerString"); + String event = "HeLlO wOrLd"; + Context context = new TestContext(); + HandlerString handler = new HandlerString(); + assertEquals("hello world", handler.handleRequest(event, context)); + } + + @Test + void testHandlerWeatherData() { + logger.info("Invoke TEST - HandlerWeatherData"); + WeatherData inputData = new WeatherData(); + inputData.setTemperatureK(298); + Context context = new TestContext(); + HandlerWeatherData handler = new HandlerWeatherData(); + WeatherData outputData = handler.handleRequest(inputData, context); + assertNotNull(outputData.getHumidityPct()); + assertNotNull(outputData.getPressureHPa()); + assertNotNull(outputData.getWindKmh()); + assertEquals(300, outputData.getTemperatureK()); + } } diff --git a/sample-apps/java-basic/template-mvn.yml b/sample-apps/java-basic/template-mvn.yml index 0eafe8e7..8718e1fc 100644 --- a/sample-apps/java-basic/template-mvn.yml +++ b/sample-apps/java-basic/template-mvn.yml @@ -7,14 +7,14 @@ Resources: Properties: CodeUri: target/java-basic-1.0-SNAPSHOT.jar Handler: example.Handler - Runtime: java8 + Runtime: java21 Description: Java function - MemorySize: 512 + MemorySize: 2048 Timeout: 10 # Function's execution role Policies: - AWSLambdaBasicExecutionRole - - AWSLambdaReadOnlyAccess + - AWSLambda_ReadOnlyAccess - AWSXrayWriteOnlyAccess - AWSLambdaVPCAccessExecutionRole Tracing: Active diff --git a/sample-apps/java-basic/template.yml b/sample-apps/java-basic/template.yml index 5a760a43..f657a99f 100644 --- a/sample-apps/java-basic/template.yml +++ b/sample-apps/java-basic/template.yml @@ -7,14 +7,14 @@ Resources: Properties: CodeUri: build/distributions/java-basic.zip Handler: example.Handler - Runtime: java8 + Runtime: java21 Description: Java function - MemorySize: 512 + MemorySize: 2048 Timeout: 10 # Function's execution role Policies: - AWSLambdaBasicExecutionRole - - AWSLambdaReadOnlyAccess + - AWSLambda_ReadOnlyAccess - AWSXrayWriteOnlyAccess - AWSLambdaVPCAccessExecutionRole Tracing: Active diff --git a/sample-apps/java-events-v1sdk/1-create-bucket.sh b/sample-apps/java-events-v1sdk/1-create-bucket.sh deleted file mode 100755 index 64a5f749..00000000 --- a/sample-apps/java-events-v1sdk/1-create-bucket.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/bash -BUCKET_ID=$(dd if=/dev/random bs=8 count=1 2>/dev/null | od -An -tx1 | tr -d ' \t\n') -BUCKET_NAME=lambda-artifacts-$BUCKET_ID -echo $BUCKET_NAME > bucket-name.txt -aws s3 mb s3://$BUCKET_NAME diff --git a/sample-apps/java-events-v1sdk/2-build-layer.sh b/sample-apps/java-events-v1sdk/2-build-layer.sh deleted file mode 100755 index 9f038396..00000000 --- a/sample-apps/java-events-v1sdk/2-build-layer.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/bash -set -eo pipefail -gradle -q packageLibs -mv build/distributions/java-events-v1sdk.zip build/java-events-v1sdk-lib.zip \ No newline at end of file diff --git a/sample-apps/java-events-v1sdk/3-deploy.sh b/sample-apps/java-events-v1sdk/3-deploy.sh deleted file mode 100755 index 5ce8d160..00000000 --- a/sample-apps/java-events-v1sdk/3-deploy.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/bash -set -eo pipefail -ARTIFACT_BUCKET=$(cat bucket-name.txt) -TEMPLATE=template.yml -if [ $1 ] -then - if [ $1 = mvn ] - then - TEMPLATE=template-mvn.yml - mvn package - fi -else - gradle build -i -fi -aws cloudformation package --template-file $TEMPLATE --s3-bucket $ARTIFACT_BUCKET --output-template-file out.yml -aws cloudformation deploy --template-file out.yml --stack-name java-events-v1sdk --capabilities CAPABILITY_NAMED_IAM diff --git a/sample-apps/java-events-v1sdk/4-invoke.sh b/sample-apps/java-events-v1sdk/4-invoke.sh deleted file mode 100755 index 5c49938d..00000000 --- a/sample-apps/java-events-v1sdk/4-invoke.sh +++ /dev/null @@ -1,28 +0,0 @@ -#!/bin/bash -set -eo pipefail -FUNCTION=$(aws cloudformation describe-stack-resource --stack-name java-events-v1sdk --logical-resource-id function --query 'StackResourceDetail.PhysicalResourceId' --output text) -if [ $1 ] -then - case $1 in - ddb) - PAYLOAD='file://events/dynamodb-record.json' - ;; - kin) - PAYLOAD='file://events/kinesis-record.json' - ;; - *) - echo -n "Unknown event type" - ;; - esac -fi -while true; do - if [ $PAYLOAD ] - then - aws lambda invoke --function-name $FUNCTION --payload $PAYLOAD out.json - else - aws lambda invoke --function-name $FUNCTION --payload file://event.json out.json - fi - cat out.json - echo "" - sleep 2 -done diff --git a/sample-apps/java-events-v1sdk/5-cleanup.sh b/sample-apps/java-events-v1sdk/5-cleanup.sh deleted file mode 100755 index 79b326e4..00000000 --- a/sample-apps/java-events-v1sdk/5-cleanup.sh +++ /dev/null @@ -1,38 +0,0 @@ -#!/bin/bash -set -eo pipefail -STACK=java-events-v1sdk -if [[ $# -eq 1 ]] ; then - STACK=$1 - echo "Deleting stack $STACK" -fi -FUNCTION=$(aws cloudformation describe-stack-resource --stack-name $STACK --logical-resource-id function --query 'StackResourceDetail.PhysicalResourceId' --output text) -aws cloudformation delete-stack --stack-name $STACK -echo "Deleted $STACK stack." - -if [ -f bucket-name.txt ]; then - ARTIFACT_BUCKET=$(cat bucket-name.txt) - if [[ ! $ARTIFACT_BUCKET =~ lambda-artifacts-[a-z0-9]{16} ]] ; then - echo "Bucket was not created by this application. Skipping." - else - while true; do - read -p "Delete deployment artifacts and bucket ($ARTIFACT_BUCKET)? (y/n)" response - case $response in - [Yy]* ) aws s3 rb --force s3://$ARTIFACT_BUCKET; rm bucket-name.txt; break;; - [Nn]* ) break;; - * ) echo "Response must start with y or n.";; - esac - done - fi -fi - -while true; do - read -p "Delete function log group (/aws/lambda/$FUNCTION)? (y/n)" response - case $response in - [Yy]* ) aws logs delete-log-group --log-group-name /aws/lambda/$FUNCTION; break;; - [Nn]* ) break;; - * ) echo "Response must start with y or n.";; - esac -done - -rm -f out.yml out.json -rm -rf build .gradle target diff --git a/sample-apps/java-events-v1sdk/README.md b/sample-apps/java-events-v1sdk/README.md deleted file mode 100644 index 3d9ab2ed..00000000 --- a/sample-apps/java-events-v1sdk/README.md +++ /dev/null @@ -1,109 +0,0 @@ -# Basic function with event library types and the AWS SDK (Java) - -This sample application shows the use of the `aws-lambda-java-events` library with event types that require AWS SDK as a dependency. A separate handler class is defined for each input type. For other event types (which don't require the AWS SDK), see the `java-events` sample. - -![Architecture](/sample-apps/java-events-v1sdk/images/sample-java-events-v1sdk.png) - -The project includes function code and supporting resources: -- `src/main` - A Java function. -- `src/test` - A unit test and helper classes. -- `template.yml` - An AWS CloudFormation template that creates an application. -- `build.gradle` - A Gradle build file. -- `pom.xml` - A Maven build file. -- `1-create-bucket.sh`, `2-build-layer.sh`, etc. - Shell scripts that use the AWS CLI to deploy and manage the application. - -Use the following instructions to deploy the sample application. - -# Requirements -- [Java 8 runtime environment (SE JRE)](https://www.oracle.com/java/technologies/javase-downloads.html) -- [Gradle 5](https://gradle.org/releases/) or [Maven 3](https://maven.apache.org/docs/history.html) -- The Bash shell. For Linux and macOS, this is included by default. In Windows 10, you can install the [Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows-integrated version of Ubuntu and Bash. -- [The AWS CLI v1](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html). - -# Setup -Download or clone this repository. - - $ git clone https://github.com/awsdocs/aws-lambda-developer-guide.git - $ cd aws-lambda-developer-guide/sample-apps/java-events-v1sdk - -Run `1-create-bucket.sh` to create a new bucket for deployment artifacts. - - java-events-v1sdk$ ./1-create-bucket.sh - make_bucket: lambda-artifacts-a5e4xmplb5b22e0d - -To build a Lambda layer that contains the function's runtime dependencies, run `2-build-layer.sh`. Packaging dependencies in a layer reduces the size of the deployment package that you upload when you modify your code. - - java-events-v1sdk$ ./2-build-layer.sh - -# Deploy -Run `3-deploy.sh` to build the application with Gradle and deploy it. - - java-events-v1sdk$ ./3-deploy.sh - BUILD SUCCESSFUL in 1s - Successfully packaged artifacts and wrote output template to file out.yml. - Waiting for changeset to be created.. - Successfully created/updated stack - java-events-v1sdk - -This script uses AWS CloudFormation to deploy the Lambda functions and an IAM role. If the AWS CloudFormation stack that contains the resources already exists, the script updates it with any changes to the template or function code. - -You can also build the application with Maven. To use maven, add `mvn` to the command. - - java-events-v1sdk$ ./3-deploy.sh mvn - [INFO] Scanning for projects... - [INFO] -----------------------< com.example:java-events-v1sdk >----------------------- - [INFO] Building java-events-v1sdk-function 1.0-SNAPSHOT - [INFO] --------------------------------[ jar ]--------------------------------- - ... - -# Test -Run `4-invoke.sh` to invoke the function. - - java-events-v1sdk$ ./4-invoke.sh - { - "StatusCode": 200, - "ExecutedVersion": "$LATEST" - } - "200 OK" - -Let the script invoke the function a few times and then press `CRTL+C` to exit. - -The application uses AWS X-Ray to trace requests. Open the [X-Ray console](https://console.aws.amazon.com/xray/home#/service-map) to view the service map. - -![Service Map](/sample-apps/java-events-v1sdk/images/java-events-v1sdk-servicemap.png) - -Choose a node in the main function graph. Then choose **View traces** to see a list of traces. Choose any trace to view a timeline that breaks down the work done by the function. - -![Trace](/sample-apps/java-events-v1sdk/images/java-events-v1sdk-trace.png) - -# Configure Handler Class - -By default, the function uses a handler class named `Handler` that takes an Amazon S3 notification event as input and returns a string. The project also includes handlers that use other input and output types. The handlers are defined in the following files under `src/main/java/example`: - -- `Handler.java` - Takes `S3Event` as input. -- `HandlerDynamoDB.java` - Takes `DynamoDBEvent` as input. -- `HandlerKinesis.java` - Takes `KinesisEvent` as input. - -To use a different handler, change the value of the Handler setting in the application template (`template.yml` or `template-mvn.yaml`). For example, to use the Kinesis handler: - - Properties: - CodeUri: build/distributions/java-events-v1sdk.zip - Handler: example.HandlerKinesis - -Deploy the change, and then use the invoke script to test the new configuration. Pass the handler type key as an argument to the invoke script. - - ./4-invoke.sh kin - { - "StatusCode": 200, - "ExecutedVersion": "$LATEST" - } - "200 OK" - -The following event type keys are supported: -- none - S3 notification (`events/s3-notification.json`) -- `kin` - Kinesis record (`events/kinesis-record.json`) -- `ddb` - DynamoDB record (`events/dynamodb-record.json`) - -# Cleanup -To delete the application, run `5-cleanup.sh`. - - java-events-v1sdk$ ./5-cleanup.sh diff --git a/sample-apps/java-events-v1sdk/build.gradle b/sample-apps/java-events-v1sdk/build.gradle deleted file mode 100644 index 9a0f649e..00000000 --- a/sample-apps/java-events-v1sdk/build.gradle +++ /dev/null @@ -1,56 +0,0 @@ -plugins { - id 'java' -} - -repositories { - mavenCentral() -} - -dependencies { - implementation platform('com.amazonaws:aws-xray-recorder-sdk-bom:2.4.0') - implementation 'com.amazonaws:aws-lambda-java-core:1.2.0' - implementation 'com.amazonaws:aws-lambda-java-events:2.2.7' - implementation 'com.amazonaws:aws-java-sdk-s3:1.11.578' - implementation 'com.amazonaws:aws-java-sdk-kinesis:1.11.578' - implementation 'com.amazonaws:aws-java-sdk-dynamodb:1.11.578' - implementation 'com.amazonaws:aws-xray-recorder-sdk-core' - implementation 'com.amazonaws:aws-xray-recorder-sdk-aws-sdk' - implementation 'com.amazonaws:aws-xray-recorder-sdk-aws-sdk-instrumentor' - implementation 'com.google.code.gson:gson:2.8.6' - implementation 'org.apache.logging.log4j:log4j-api:2.13.0' - implementation 'org.apache.logging.log4j:log4j-core:2.13.0' - implementation 'org.apache.logging.log4j:log4j-slf4j18-impl:2.13.0' - runtimeOnly 'com.amazonaws:aws-lambda-java-log4j2:1.1.0' - testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0' - testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.6.0' -} - -test { - useJUnitPlatform() -} - -task packageBig(type: Zip) { - from compileJava - from processResources - into('lib') { - from configurations.runtimeClasspath - } -} - -task packageLibs(type: Zip) { - into('java/lib') { - from configurations.runtimeClasspath - } -} - -task packageSmall(type: Zip) { - from compileJava - from processResources -} - -java { - sourceCompatibility = JavaVersion.VERSION_1_8 - targetCompatibility = JavaVersion.VERSION_1_8 -} - -build.dependsOn packageSmall \ No newline at end of file diff --git a/sample-apps/java-events-v1sdk/images/java-events-v1sdk-servicemap.png b/sample-apps/java-events-v1sdk/images/java-events-v1sdk-servicemap.png deleted file mode 100644 index 72afcfdb..00000000 Binary files a/sample-apps/java-events-v1sdk/images/java-events-v1sdk-servicemap.png and /dev/null differ diff --git a/sample-apps/java-events-v1sdk/images/java-events-v1sdk-trace.png b/sample-apps/java-events-v1sdk/images/java-events-v1sdk-trace.png deleted file mode 100644 index 4f921833..00000000 Binary files a/sample-apps/java-events-v1sdk/images/java-events-v1sdk-trace.png and /dev/null differ diff --git a/sample-apps/java-events-v1sdk/images/sample-java-events-v1sdk.png b/sample-apps/java-events-v1sdk/images/sample-java-events-v1sdk.png deleted file mode 100644 index 84349fbb..00000000 Binary files a/sample-apps/java-events-v1sdk/images/sample-java-events-v1sdk.png and /dev/null differ diff --git a/sample-apps/java-events-v1sdk/pom.xml b/sample-apps/java-events-v1sdk/pom.xml deleted file mode 100644 index a412ae11..00000000 --- a/sample-apps/java-events-v1sdk/pom.xml +++ /dev/null @@ -1,140 +0,0 @@ - - 4.0.0 - com.example - java-events-v1sdk - jar - 1.0-SNAPSHOT - java-events-v1sdk-function - - UTF-8 - 1.8 - 1.8 - - - - com.amazonaws - aws-lambda-java-core - 1.2.0 - - - com.amazonaws - aws-lambda-java-events - 2.2.7 - - - com.amazonaws - aws-lambda-java-log4j2 - 1.1.0 - - - com.google.code.gson - gson - 2.8.6 - - - org.apache.logging.log4j - log4j-api - 2.13.0 - - - org.apache.logging.log4j - log4j-core - 2.13.0 - - - org.apache.logging.log4j - log4j-slf4j18-impl - 2.13.0 - - - com.amazonaws - aws-java-sdk-s3 - 1.11.578 - - - com.amazonaws - aws-java-sdk-kinesis - 1.11.578 - - - com.amazonaws - aws-java-sdk-dynamodb - 1.11.578 - - - com.amazonaws - aws-xray-recorder-sdk-aws-sdk-core - 2.4.0 - - - com.amazonaws - aws-xray-recorder-sdk-aws-sdk - 2.4.0 - - - com.amazonaws - aws-xray-recorder-sdk-aws-sdk-instrumentor - 2.4.0 - - - org.junit.jupiter - junit-jupiter-api - 5.6.0 - test - - - org.junit.jupiter - junit-jupiter-engine - 5.6.0 - test - - - - - - - maven-surefire-plugin - 2.22.2 - - - org.apache.maven.plugins - maven-shade-plugin - 3.2.2 - - false - - - - package - - shade - - - - - - - - - - - - com.github.edwgiz - maven-shade-plugin.log4j2-cachefile-transformer - 2.13.0 - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.1 - - 1.8 - 1.8 - - - - - \ No newline at end of file diff --git a/sample-apps/java-events-v1sdk/src/main/java/example/Handler.java b/sample-apps/java-events-v1sdk/src/main/java/example/Handler.java deleted file mode 100644 index 7323c91b..00000000 --- a/sample-apps/java-events-v1sdk/src/main/java/example/Handler.java +++ /dev/null @@ -1,35 +0,0 @@ -package example; - -import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; -import com.amazonaws.services.lambda.runtime.LambdaLogger; -import com.amazonaws.services.lambda.runtime.events.S3Event; - -import com.amazonaws.services.s3.event.S3EventNotification.S3EventNotificationRecord; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -// Handler value: example.Handler -public class Handler implements RequestHandler{ - private static final Logger logger = LoggerFactory.getLogger(Handler.class); - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - @Override - public String handleRequest(S3Event event, Context context) - { - String response = new String("200 OK"); - S3EventNotificationRecord record = event.getRecords().get(0); - String srcBucket = record.getS3().getBucket().getName(); - // Object key may have spaces or unicode non-ASCII characters. - String srcKey = record.getS3().getObject().getUrlDecodedKey(); - logger.info("RECORD: " + record); - logger.info("SOURCE BUCKET: " + srcBucket); - logger.info("SOURCE KEY: " + srcKey); - // log execution details - Util.logEnvironment(event, context, gson); - return response; - } -} \ No newline at end of file diff --git a/sample-apps/java-events-v1sdk/src/main/java/example/HandlerDynamoDB.java b/sample-apps/java-events-v1sdk/src/main/java/example/HandlerDynamoDB.java deleted file mode 100644 index 9cf234c1..00000000 --- a/sample-apps/java-events-v1sdk/src/main/java/example/HandlerDynamoDB.java +++ /dev/null @@ -1,35 +0,0 @@ -package example; - -import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; -import com.amazonaws.services.lambda.runtime.LambdaLogger; -import com.amazonaws.services.lambda.runtime.events.DynamodbEvent; -import com.amazonaws.services.lambda.runtime.events.DynamodbEvent.DynamodbStreamRecord; - -import com.amazonaws.services.dynamodbv2.model.Record; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -// Handler value: example.HandlerDynamoDB -public class HandlerDynamoDB implements RequestHandler{ - private static final Logger logger = LoggerFactory.getLogger(HandlerDynamoDB.class); - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - @Override - public String handleRequest(DynamodbEvent event, Context context) - { - String response = new String("200 OK"); - for (DynamodbStreamRecord record : event.getRecords()){ - logger.info(record.getEventID()); - logger.info(record.getEventName()); - logger.info(record.getDynamodb().toString()); - } - logger.info("Successfully processed " + event.getRecords().size() + " records."); - // log execution details - Util.logEnvironment(event, context, gson); - return response; - } -} \ No newline at end of file diff --git a/sample-apps/java-events-v1sdk/src/main/java/example/Util.java b/sample-apps/java-events-v1sdk/src/main/java/example/Util.java deleted file mode 100644 index 2e11f51e..00000000 --- a/sample-apps/java-events-v1sdk/src/main/java/example/Util.java +++ /dev/null @@ -1,23 +0,0 @@ -package example; - -import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.LambdaLogger; - -import com.google.gson.Gson; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class Util { - private static final Logger logger = LoggerFactory.getLogger(Util.class); - - public static void logEnvironment(Object event, Context context, Gson gson) - { - // log execution details - logger.info("ENVIRONMENT VARIABLES: " + gson.toJson(System.getenv())); - logger.info("CONTEXT: " + gson.toJson(context)); - // log event details - logger.info("EVENT: " + gson.toJson(event)); - logger.info("EVENT TYPE: " + event.getClass().toString()); - } -} \ No newline at end of file diff --git a/sample-apps/java-events-v1sdk/src/main/resources/log4j2.xml b/sample-apps/java-events-v1sdk/src/main/resources/log4j2.xml deleted file mode 100644 index b9a6c317..00000000 --- a/sample-apps/java-events-v1sdk/src/main/resources/log4j2.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - %d{yyyy-MM-dd HH:mm:ss} %X{AWSRequestId} %-5p %c{1} - %m%n - - - - - - - - - - - \ No newline at end of file diff --git a/sample-apps/java-events-v1sdk/src/test/java/example/InvokeTest.java b/sample-apps/java-events-v1sdk/src/test/java/example/InvokeTest.java deleted file mode 100644 index 0faa1846..00000000 --- a/sample-apps/java-events-v1sdk/src/test/java/example/InvokeTest.java +++ /dev/null @@ -1,79 +0,0 @@ -package example; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.jupiter.api.Test; - -import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.LambdaLogger; -import com.amazonaws.services.lambda.runtime.RequestHandler; -import com.amazonaws.services.lambda.runtime.events.S3Event; -import com.amazonaws.services.s3.event.S3EventNotification; -import com.amazonaws.services.s3.event.S3EventNotification.S3EventNotificationRecord; -import com.amazonaws.services.s3.event.S3EventNotification.RequestParametersEntity; -import com.amazonaws.services.s3.event.S3EventNotification.ResponseElementsEntity; -import com.amazonaws.services.s3.event.S3EventNotification.S3Entity; -import com.amazonaws.services.s3.event.S3EventNotification.UserIdentityEntity; -import com.amazonaws.services.s3.event.S3EventNotification.GlacierEventDataEntity; -import com.amazonaws.services.s3.event.S3EventNotification.S3BucketEntity; -import com.amazonaws.services.s3.event.S3EventNotification.S3ObjectEntity; -import com.amazonaws.services.s3.event.S3EventNotification.UserIdentityEntity; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.List; -import java.util.ArrayList; -import java.lang.Long; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.io.IOException; - -import com.amazonaws.xray.AWSXRay; -import com.amazonaws.xray.AWSXRayRecorderBuilder; -import com.amazonaws.xray.strategy.sampling.NoSamplingStrategy; - -class InvokeTest { - private static final Logger logger = LoggerFactory.getLogger(InvokeTest.class); - - public InvokeTest() { - AWSXRayRecorderBuilder builder = AWSXRayRecorderBuilder.standard(); - builder.withSamplingStrategy(new NoSamplingStrategy()); - AWSXRay.setGlobalRecorder(builder.build()); - } - - @Test - void invokeTest() throws IOException { - AWSXRay.beginSegment("java-s3-test"); - String bucket = new String(Files.readAllLines(Paths.get("bucket-name.txt")).get(0)); - S3EventNotificationRecord record = new S3EventNotificationRecord("us-east-2", - "ObjectCreated:Put", - "aws:s3", - "2020-03-08T00:30:12.456Z", - "2.1", - new RequestParametersEntity("174.255.255.156"), - new ResponseElementsEntity("nBbLJPAHhdvxmplPvtCgTrWCqf/KtonyV93l9rcoMLeIWJxpS9x9P8u01+Tj0OdbAoGs+VGvEvWl/Sg1NW5uEsVO25Laq7L", "AF2D7AB6002E898D"), - new S3Entity("682bbb7a-xmpl-48ca-94b1-7f77c4d6dbf0", - new S3BucketEntity(bucket, - new UserIdentityEntity("A3XMPLFAF2AI3E"), - "arn:aws:s3:::" + bucket), - new S3ObjectEntity("inbound/sample-java-s3.png", - new Long(21476), - "d132690b6c65b6d1629721dcfb49b883", - "", - "005E64A65DF093B26D"), - "1.0"), - new UserIdentityEntity("AWS:AIDAINPONIXMPLT3IKHL2")); - ArrayList records = new ArrayList(); - records.add(record); - S3Event event = new S3Event(records); - - Context context = new TestContext(); - String requestId = context.getAwsRequestId(); - Handler handler = new Handler(); - String result = handler.handleRequest(event, context); - assertTrue(result.contains("200 OK")); - AWSXRay.endSegment(); - } - -} diff --git a/sample-apps/java-events-v1sdk/src/test/java/example/TestContext.java b/sample-apps/java-events-v1sdk/src/test/java/example/TestContext.java deleted file mode 100644 index 69e0af00..00000000 --- a/sample-apps/java-events-v1sdk/src/test/java/example/TestContext.java +++ /dev/null @@ -1,45 +0,0 @@ -package example; - -import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.CognitoIdentity; -import com.amazonaws.services.lambda.runtime.ClientContext; -import com.amazonaws.services.lambda.runtime.LambdaLogger; - -public class TestContext implements Context{ - - public TestContext() {} - public String getAwsRequestId(){ - return new String("495b12a8-xmpl-4eca-8168-160484189f99"); - } - public String getLogGroupName(){ - return new String("/aws/lambda/my-function"); - } - public String getLogStreamName(){ - return new String("2020/02/26/[$LATEST]704f8dxmpla04097b9134246b8438f1a"); - } - public String getFunctionName(){ - return new String("my-function"); - } - public String getFunctionVersion(){ - return new String("$LATEST"); - } - public String getInvokedFunctionArn(){ - return new String("arn:aws:lambda:us-east-2:123456789012:function:my-function"); - } - public CognitoIdentity getIdentity(){ - return null; - } - public ClientContext getClientContext(){ - return null; - } - public int getRemainingTimeInMillis(){ - return 300000; - } - public int getMemoryLimitInMB(){ - return 512; - } - public LambdaLogger getLogger(){ - return new TestLogger(); - } - -} \ No newline at end of file diff --git a/sample-apps/java-events-v1sdk/src/test/java/example/TestLogger.java b/sample-apps/java-events-v1sdk/src/test/java/example/TestLogger.java deleted file mode 100644 index 1d3c8efc..00000000 --- a/sample-apps/java-events-v1sdk/src/test/java/example/TestLogger.java +++ /dev/null @@ -1,14 +0,0 @@ -package example; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import com.amazonaws.services.lambda.runtime.LambdaLogger; - -public class TestLogger implements LambdaLogger { - private static final Logger logger = LoggerFactory.getLogger(TestLogger.class); - public void log(String message){ - logger.info(message); - } - public void log(byte[] message){ - logger.info(new String(message)); - } -} diff --git a/sample-apps/java-events-v1sdk/src/test/resources/log4j2.xml b/sample-apps/java-events-v1sdk/src/test/resources/log4j2.xml deleted file mode 100644 index 3b69545f..00000000 --- a/sample-apps/java-events-v1sdk/src/test/resources/log4j2.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/sample-apps/java-events-v1sdk/template-mvn.yml b/sample-apps/java-events-v1sdk/template-mvn.yml deleted file mode 100644 index ee250ed0..00000000 --- a/sample-apps/java-events-v1sdk/template-mvn.yml +++ /dev/null @@ -1,20 +0,0 @@ -AWSTemplateFormatVersion: '2010-09-09' -Transform: 'AWS::Serverless-2016-10-31' -Description: An AWS Lambda application that calls the Lambda API. -Resources: - function: - Type: AWS::Serverless::Function - Properties: - CodeUri: target/java-events-v1sdk-1.0-SNAPSHOT.jar - Handler: example.Handler - Runtime: java8 - Description: Java function - MemorySize: 512 - Timeout: 15 - # Function's execution role - Policies: - - AWSLambdaBasicExecutionRole - - AWSLambdaReadOnlyAccess - - AWSXrayWriteOnlyAccess - - AWSLambdaVPCAccessExecutionRole - Tracing: Active diff --git a/sample-apps/java-events-v1sdk/template.yml b/sample-apps/java-events-v1sdk/template.yml deleted file mode 100644 index 40b167f1..00000000 --- a/sample-apps/java-events-v1sdk/template.yml +++ /dev/null @@ -1,30 +0,0 @@ -AWSTemplateFormatVersion: '2010-09-09' -Transform: 'AWS::Serverless-2016-10-31' -Description: An AWS Lambda application that calls the Lambda API. -Resources: - function: - Type: AWS::Serverless::Function - Properties: - CodeUri: build/distributions/java-events-v1sdk.zip - Handler: example.Handler - Runtime: java8 - Description: Java function - MemorySize: 512 - Timeout: 15 - # Function's execution role - Policies: - - AWSLambdaBasicExecutionRole - - AWSLambdaReadOnlyAccess - - AWSXrayWriteOnlyAccess - - AWSLambdaVPCAccessExecutionRole - Tracing: Active - Layers: - - !Ref libs - libs: - Type: AWS::Serverless::LayerVersion - Properties: - LayerName: java-events-v1sdk-lib - Description: Dependencies for the Java S3 sample app. - ContentUri: build/java-events-v1sdk-lib.zip - CompatibleRuntimes: - - java8 diff --git a/sample-apps/java-events/3-invoke.sh b/sample-apps/java-events/3-invoke.sh index ebac190b..3dfd78e6 100755 --- a/sample-apps/java-events/3-invoke.sh +++ b/sample-apps/java-events/3-invoke.sh @@ -5,31 +5,46 @@ if [ $1 ] then case $1 in apig) - PAYLOAD='file://events/apigateway-v1.json' + PAYLOAD='fileb://events/apigateway-v1.json' ;; cws) - PAYLOAD='file://events/cloudwatch-scheduled.json' + PAYLOAD='fileb://events/cloudwatch-scheduled.json' ;; cwl) - PAYLOAD='file://events/cloudwatch-logs.json' + PAYLOAD='fileb://events/cloudwatch-logs.json' ;; sns) - PAYLOAD='file://events/sns-notification.json' + PAYLOAD='fileb://events/sns-notification.json' + ;; + cdn) + PAYLOAD='fileb://events/cloudfront.json' ;; cfg) - PAYLOAD='file://events/config-rule.json' + PAYLOAD='fileb://events/config-rule.json' ;; cc) - PAYLOAD='file://events/codecommit-push.json' + PAYLOAD='fileb://events/codecommit-push.json' ;; cog) - PAYLOAD='file://events/cognito-sync.json' + PAYLOAD='fileb://events/cognito-sync.json' + ;; + kin) + PAYLOAD='fileb://events/kinesis-record.json' ;; fh) - PAYLOAD='file://events/firehose-record.json' + PAYLOAD='fileb://events/firehose-record.json' ;; lex) - PAYLOAD='file://events/lex-flowers.json' + PAYLOAD='fileb://events/lex-flowers.json' + ;; + ddb) + PAYLOAD='fileb://events/dynamodb-record.json' + ;; + s3) + PAYLOAD='fileb://events/s3-notification.json' + ;; + sqs) + PAYLOAD='fileb://events/sqs-record.json' ;; *) echo -n "Unknown event type" @@ -41,7 +56,7 @@ while true; do then aws lambda invoke --function-name $FUNCTION --payload $PAYLOAD out.json else - aws lambda invoke --function-name $FUNCTION --payload file://event.json out.json + aws lambda invoke --function-name $FUNCTION --payload fileb://event.json out.json fi cat out.json echo "" diff --git a/sample-apps/java-events/README.md b/sample-apps/java-events/README.md index 5b72d742..edfc006b 100644 --- a/sample-apps/java-events/README.md +++ b/sample-apps/java-events/README.md @@ -2,6 +2,8 @@ This sample application shows the use of the `aws-lambda-java-events` library with various event types. To keep the deployment size minimal, it includes only types that can be used without adding the AWS SDK as a dependency. A separate handler class is defined for each input type. +**Note: To use these examples, you must be using version 3.0.0 or newer of the `aws-lambda-java-events` dependency.** If you are on an older version, see the [`java-events-v1sdk` package](https://github.com/awsdocs/aws-lambda-developer-guide/tree/main/sample-apps/java-events-v1sdk) for deprecated examples. If possible, update your `aws-lambda-java-events` dependency to version 3.0.0 or newer. + ![Architecture](/sample-apps/java-events/images/sample-java-events.png) The project includes function code and supporting resources: @@ -18,7 +20,7 @@ Use the following instructions to deploy the sample application. - [Java 8 runtime environment (SE JRE)](https://www.oracle.com/java/technologies/javase-downloads.html) - [Gradle 5](https://gradle.org/releases/) or [Maven 3](https://maven.apache.org/docs/history.html) - The Bash shell. For Linux and macOS, this is included by default. In Windows 10, you can install the [Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows-integrated version of Ubuntu and Bash. -- [The AWS CLI v1](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html). +- [The AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html) v1.17 or newer. # Setup Download or clone this repository. @@ -82,9 +84,13 @@ By default, the function uses a handler class named `Handler` that takes an API - `HandlerCognito.java` - Takes `CognitoEvent` as input. - `HandlerCWEvents.java` - Takes `ScheduledEventEvent` as input. - `HandlerCWLogs.java` - Takes `CloudWatchLogsEvent` as input. +- `HandlerDynamoDB.java` - Takes `DynamodbEvent` as input. - `HandlerFirehose.java` - Takes `KinesisFirehoseEvent` as input. +- `HandlerKinesis.java` - Takes `KinesisEvent` as input. - `HandlerLex.java` - Takes `LexEvent` as input. +- `HandlerS3.java` - Takes `S3Event` as input. - `HandlerSNS.java` - Takes `SNSEvent` as input. +- `HandlerSQS.java` - Takes `SQSEvent` as input. To use a different handler, change the value of the Handler setting in the application template (`template.yml` or `template-mvn.yaml`). For example, to use the Amazon Lex handler: @@ -110,8 +116,12 @@ The following event type keys are supported: - `cfg` - Config rule (`events/config-rule.json`) - `cc` - CodeCommit push (`events/codecommit-push.json`) - `cog` - Cognito Sync (`events/cognito-sync.json`) +- `kin` - Kinesis record (`events/kinesis-record.json`) - `fh` - Kinesis Firehose record (`events/firehose-record.json`) - `lex` - Lex dialog (`events/lex-flowers.json`) +- `ddb` - DynamoDB record (`events/dynamodb-record.json`) +- `s3` - S3Event record (`events/s3-notification.json`) +- `sqs` - SQSEvent record (`events/sqs-record.json`) # Cleanup To delete the application, run `4-cleanup.sh`. diff --git a/sample-apps/java-events/build.gradle b/sample-apps/java-events/build.gradle index ae45cb3a..acec6a6d 100644 --- a/sample-apps/java-events/build.gradle +++ b/sample-apps/java-events/build.gradle @@ -7,14 +7,13 @@ repositories { } dependencies { - implementation 'com.amazonaws:aws-lambda-java-core:1.2.0' - implementation 'com.amazonaws:aws-lambda-java-events:2.2.7' - implementation 'com.google.code.gson:gson:2.8.6' - testImplementation 'org.apache.logging.log4j:log4j-api:2.13.0' - testImplementation 'org.apache.logging.log4j:log4j-core:2.13.0' - testImplementation 'org.apache.logging.log4j:log4j-slf4j18-impl:2.13.0' - testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0' - testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.6.0' + implementation 'com.amazonaws:aws-lambda-java-core:1.2.1' + implementation 'com.amazonaws:aws-lambda-java-events:3.11.0' + implementation 'com.google.code.gson:gson:2.8.9' + implementation 'org.slf4j:slf4j-nop:2.0.6' + testImplementation 'com.amazonaws:aws-lambda-java-tests:1.1.1' + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.2' + testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.2' } test { @@ -30,8 +29,8 @@ task buildZip(type: Zip) { } java { - sourceCompatibility = JavaVersion.VERSION_1_8 - targetCompatibility = JavaVersion.VERSION_1_8 + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 } build.dependsOn buildZip diff --git a/sample-apps/java-events/events/apigateway-v1.json b/sample-apps/java-events/events/apigateway-v1.json index 7a1e2b8f..1e5e8dab 100644 --- a/sample-apps/java-events/events/apigateway-v1.json +++ b/sample-apps/java-events/events/apigateway-v1.json @@ -96,6 +96,6 @@ "domainName": "70ixmpl4fl.execute-api.us-east-2.amazonaws.com", "apiId": "70ixmpl4fl" }, - "body": null, + "body": "Hello world!", "isBase64Encoded": false } \ No newline at end of file diff --git a/sample-apps/java-events/events/apigateway-v2.json b/sample-apps/java-events/events/apigateway-v2.json index 4a9a547f..a009c4bf 100644 --- a/sample-apps/java-events/events/apigateway-v2.json +++ b/sample-apps/java-events/events/apigateway-v2.json @@ -42,5 +42,6 @@ "time": "10/Mar/2020:05:16:23 +0000", "timeEpoch": 1583817383220 }, + "body": "Hello world!", "isBase64Encoded": true } \ No newline at end of file diff --git a/sample-apps/java-events/events/cloudfront.json b/sample-apps/java-events/events/cloudfront.json new file mode 100644 index 00000000..3dbc92d6 --- /dev/null +++ b/sample-apps/java-events/events/cloudfront.json @@ -0,0 +1,40 @@ +{ + "Records": [ + { + "cf": { + "config": { + "distributionDomainName": "d111111abcdef8.cloudfront.net", + "distributionId": "EDFDVBD6EXAMPLE", + "eventType": "viewer-request", + "requestId": "4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==" + }, + "request": { + "clientIp": "203.0.113.178", + "headers": { + "host": [ + { + "key": "Host", + "value": "d111111abcdef8.cloudfront.net" + } + ], + "user-agent": [ + { + "key": "User-Agent", + "value": "curl/7.66.0" + } + ], + "accept": [ + { + "key": "accept", + "value": "*/*" + } + ] + }, + "method": "GET", + "querystring": "", + "uri": "/picture.jpg" + } + } + } + ] +} \ No newline at end of file diff --git a/sample-apps/java-events-v1sdk/events/dynamodb-record.json b/sample-apps/java-events/events/dynamodb-record.json similarity index 100% rename from sample-apps/java-events-v1sdk/events/dynamodb-record.json rename to sample-apps/java-events/events/dynamodb-record.json diff --git a/sample-apps/java-events-v1sdk/events/kinesis-record.json b/sample-apps/java-events/events/kinesis-record.json similarity index 100% rename from sample-apps/java-events-v1sdk/events/kinesis-record.json rename to sample-apps/java-events/events/kinesis-record.json diff --git a/sample-apps/java-events-v1sdk/events/s3-notification.json b/sample-apps/java-events/events/s3-notification.json similarity index 100% rename from sample-apps/java-events-v1sdk/events/s3-notification.json rename to sample-apps/java-events/events/s3-notification.json diff --git a/sample-apps/java-events/events/sns-notification.json b/sample-apps/java-events/events/sns-notification.json index cf8d74d9..9697ade6 100644 --- a/sample-apps/java-events/events/sns-notification.json +++ b/sample-apps/java-events/events/sns-notification.json @@ -14,7 +14,7 @@ }, "SigningCertUrl": "https://sns.us-east-2.amazonaws.com/SimpleNotificationService-a86cxmpl4e1f29c941702d737128f7b6.pem", "MessageId": "476643b1-xmpl-526c-973d-1542ba9af1d6", - "Message": "Updated and expanded documentation for using Lambda with API Gateway, including support for HTTP APIs. Added a sample application that creates an API and function with AWS CloudFormation. For details, see Using AWS Lambda with Amazon API Gateway.", + "Message": "Updated and expanded documentation for using Lambda with API Gateway, including support for HTTP APIs.", "Subject": "Latest updates from AWS Lambda", "UnsubscribeUrl": "https://sns.us-east-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-east-2:123456789012:java-events-topic:dd15418a-xmpl-4cfd-b418-f7fcb08c7ee4", "Type": "Notification", diff --git a/sample-apps/java-events/events/sqs-record.json b/sample-apps/java-events/events/sqs-record.json new file mode 100644 index 00000000..d1c7c265 --- /dev/null +++ b/sample-apps/java-events/events/sqs-record.json @@ -0,0 +1,20 @@ +{ + "Records": [ + { + "messageId": "19dd0b57-b21e-4ac1-bd88-01bbb068cb78", + "receiptHandle": "MessageReceiptHandle", + "body": "Hello from SQS!", + "attributes": { + "ApproximateReceiveCount": "1", + "SentTimestamp": "1523232000000", + "SenderId": "123456789012", + "ApproximateFirstReceiveTimestamp": "1523232000001" + }, + "messageAttributes": {}, + "md5OfBody": "7b270e59b47ff90a553787216d55d91d", + "eventSource": "aws:sqs", + "eventSourceARN": "arn:aws:sqs:us-west-2:123456789012:MyQueue", + "awsRegion": "us-west-2" + } + ] +} diff --git a/sample-apps/java-events/pom.xml b/sample-apps/java-events/pom.xml index 5a0714ab..025d54b5 100644 --- a/sample-apps/java-events/pom.xml +++ b/sample-apps/java-events/pom.xml @@ -8,55 +8,48 @@ java-events-function UTF-8 - 1.8 - 1.8 + 11 + 11 com.amazonaws aws-lambda-java-core - 1.2.0 + 1.2.1 com.amazonaws aws-lambda-java-events - 2.2.7 + 3.11.0 com.google.code.gson gson - 2.8.6 + 2.8.9 - org.apache.logging.log4j - log4j-api - 2.13.0 - test - - - org.apache.logging.log4j - log4j-core - 2.13.0 - test + org.slf4j + slf4j-nop + 2.0.6 - org.apache.logging.log4j - log4j-slf4j18-impl - 2.13.0 - test - - org.junit.jupiter junit-jupiter-api - 5.6.0 + 5.8.2 test - - + + org.junit.jupiter junit-jupiter-engine - 5.6.0 + 5.8.2 + test + + + com.amazonaws + aws-lambda-java-tests + 1.1.1 test - + @@ -71,6 +64,16 @@ 3.2.2 false + + + *:* + + module-info.class + META-INF/* + META-INF/versions/** + + + @@ -86,8 +89,8 @@ maven-compiler-plugin 3.8.1 - 1.8 - 1.8 + 11 + 11 diff --git a/sample-apps/java-events/src/main/java/example/HandlerApiGateway.java b/sample-apps/java-events/src/main/java/example/HandlerApiGatewayV1.java similarity index 66% rename from sample-apps/java-events/src/main/java/example/HandlerApiGateway.java rename to sample-apps/java-events/src/main/java/example/HandlerApiGatewayV1.java index d417e28f..c1fb1d5d 100644 --- a/sample-apps/java-events/src/main/java/example/HandlerApiGateway.java +++ b/sample-apps/java-events/src/main/java/example/HandlerApiGatewayV1.java @@ -1,35 +1,31 @@ package example; import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.LambdaLogger; +import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import java.util.Map; import java.util.HashMap; -// Handler value: example.HandlerApiGateway -public class HandlerApiGateway implements RequestHandler{ - Gson gson = new GsonBuilder().setPrettyPrinting().create(); +// Handler value: example.Handler +public class HandlerApiGatewayV1 implements RequestHandler{ + @Override public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent event, Context context) { LambdaLogger logger = context.getLogger(); + logger.log("EVENT TYPE: " + event.getClass().toString()); APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent(); response.setIsBase64Encoded(false); response.setStatusCode(200); HashMap headers = new HashMap(); headers.put("Content-Type", "text/html"); response.setHeaders(headers); - response.setBody("AWS Lambda sample"+ + String body = event.getBody() != null ? event.getBody() : "Empty body"; + response.setBody("" + body + "" + "

Welcome

Page generated by a Lambda function.

" + ""); - // log execution details - Util.logEnvironment(event, context, gson); return response; } } \ No newline at end of file diff --git a/sample-apps/java-events/src/main/java/example/Handler.java b/sample-apps/java-events/src/main/java/example/HandlerApiGatewayV2.java similarity index 51% rename from sample-apps/java-events/src/main/java/example/Handler.java rename to sample-apps/java-events/src/main/java/example/HandlerApiGatewayV2.java index bdc7064e..b8fefa86 100644 --- a/sample-apps/java-events/src/main/java/example/Handler.java +++ b/sample-apps/java-events/src/main/java/example/HandlerApiGatewayV2.java @@ -1,35 +1,31 @@ package example; import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.LambdaLogger; -import com.amazonaws.services.lambda.runtime.events.APIGatewayV2ProxyRequestEvent; -import com.amazonaws.services.lambda.runtime.events.APIGatewayV2ProxyResponseEvent; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import com.amazonaws.services.lambda.runtime.RequestHandler; +import com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPEvent; +import com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPResponse; -import java.util.Map; import java.util.HashMap; -// Handler value: example.Handler -public class Handler implements RequestHandler{ - Gson gson = new GsonBuilder().setPrettyPrinting().create(); +// Handler value: example.HandlerApiGateway +public class HandlerApiGatewayV2 implements RequestHandler{ + @Override - public APIGatewayV2ProxyResponseEvent handleRequest(APIGatewayV2ProxyRequestEvent event, Context context) + public APIGatewayV2HTTPResponse handleRequest(APIGatewayV2HTTPEvent event, Context context) { LambdaLogger logger = context.getLogger(); - APIGatewayV2ProxyResponseEvent response = new APIGatewayV2ProxyResponseEvent(); + logger.log("EVENT TYPE: " + event.getClass().toString()); + APIGatewayV2HTTPResponse response = new APIGatewayV2HTTPResponse(); response.setIsBase64Encoded(false); response.setStatusCode(200); HashMap headers = new HashMap(); headers.put("Content-Type", "text/html"); response.setHeaders(headers); - response.setBody("AWS Lambda sample"+ + String body = event.getBody() != null ? event.getBody() : "Empty body"; + response.setBody("" + body + "" + "

Welcome

Page generated by a Lambda function.

" + ""); - // log execution details - Util.logEnvironment(event, context, gson); return response; } -} \ No newline at end of file +} diff --git a/sample-apps/java-events/src/main/java/example/HandlerCWEvents.java b/sample-apps/java-events/src/main/java/example/HandlerCWEvents.java index 606af881..c052ef24 100644 --- a/sample-apps/java-events/src/main/java/example/HandlerCWEvents.java +++ b/sample-apps/java-events/src/main/java/example/HandlerCWEvents.java @@ -1,23 +1,25 @@ package example; import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.LambdaLogger; +import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.ScheduledEvent; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import java.util.ArrayList; +import java.util.List; // Handler value: example.HandlerCWEvents -public class HandlerCWEvents implements RequestHandler{ - Gson gson = new GsonBuilder().setPrettyPrinting().create(); +public class HandlerCWEvents implements RequestHandler>{ + @Override - public String handleRequest(ScheduledEvent event, Context context) + public List handleRequest(ScheduledEvent event, Context context) { LambdaLogger logger = context.getLogger(); - String response = new String("200 OK"); - // log execution details - Util.logEnvironment(event, context, gson); - return response; + logger.log("EVENT TYPE: " + event.getClass().toString()); + var resourcesFound = new ArrayList(); + for (String resource : event.getResources()) { + resourcesFound.add(resource); + } + return resourcesFound; } } \ No newline at end of file diff --git a/sample-apps/java-events/src/main/java/example/HandlerCWLogs.java b/sample-apps/java-events/src/main/java/example/HandlerCWLogs.java index e02a500b..6ce35ab5 100644 --- a/sample-apps/java-events/src/main/java/example/HandlerCWLogs.java +++ b/sample-apps/java-events/src/main/java/example/HandlerCWLogs.java @@ -1,18 +1,13 @@ package example; import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.LambdaLogger; +import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.CloudWatchLogsEvent; -import com.amazonaws.services.lambda.runtime.events.CloudWatchLogsEvent.AWSLogs; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; import java.util.Base64; import java.util.Base64.Decoder; -import java.util.zip.Inflater; - import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -22,12 +17,12 @@ // Handler value: example.HandlerCWLogs public class HandlerCWLogs implements RequestHandler{ - Gson gson = new GsonBuilder().setPrettyPrinting().create(); + @Override public String handleRequest(CloudWatchLogsEvent event, Context context) { LambdaLogger logger = context.getLogger(); - String response = new String("200 OK"); + logger.log("EVENT TYPE: " + event.getClass().toString()); Decoder decoder = Base64.getDecoder(); byte[] decodedEvent = decoder.decode(event.getAwsLogs().getData()); StringBuilder output = new StringBuilder(); @@ -36,15 +31,12 @@ public String handleRequest(CloudWatchLogsEvent event, Context context) InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); bufferedReader.lines().forEach( line -> { - logger.log(line); output.append(line); }); - logger.log(output.toString()); + // logger.info(output.toString()); } catch(IOException e) { logger.log("ERROR: " + e.toString()); } - // log execution details - Util.logEnvironment(event, context, gson); - return response; + return output.toString(); } } diff --git a/sample-apps/java-events/src/main/java/example/HandlerCloudFront.java b/sample-apps/java-events/src/main/java/example/HandlerCloudFront.java index ea465206..b48a9fd5 100644 --- a/sample-apps/java-events/src/main/java/example/HandlerCloudFront.java +++ b/sample-apps/java-events/src/main/java/example/HandlerCloudFront.java @@ -1,23 +1,28 @@ package example; import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.LambdaLogger; +import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.CloudFrontEvent; +import com.amazonaws.services.lambda.runtime.events.CloudFrontEvent.CF; +import com.amazonaws.services.lambda.runtime.events.CloudFrontEvent.Record; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import java.util.ArrayList; +import java.util.List; // Handler value: example.HandlerCloudFront -public class HandlerCloudFront implements RequestHandler{ - Gson gson = new GsonBuilder().setPrettyPrinting().create(); +public class HandlerCloudFront implements RequestHandler>{ + @Override - public String handleRequest(CloudFrontEvent event, Context context) + public List handleRequest(CloudFrontEvent event, Context context) { LambdaLogger logger = context.getLogger(); - String response = new String("200 OK"); - // log execution details - Util.logEnvironment(event, context, gson); - return response; + logger.log("EVENT TYPE: " + event.getClass().toString()); + var urisFound = new ArrayList(); + for (Record record : event.getRecords()) { + CF cfBody = record.getCf(); + urisFound.add(cfBody.getRequest().getUri()); + } + return urisFound; } } \ No newline at end of file diff --git a/sample-apps/java-events/src/main/java/example/HandlerCodeCommit.java b/sample-apps/java-events/src/main/java/example/HandlerCodeCommit.java index c9dbce03..5b5a2a5a 100644 --- a/sample-apps/java-events/src/main/java/example/HandlerCodeCommit.java +++ b/sample-apps/java-events/src/main/java/example/HandlerCodeCommit.java @@ -1,23 +1,31 @@ package example; import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.LambdaLogger; +import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.CodeCommitEvent; +import com.amazonaws.services.lambda.runtime.events.CodeCommitEvent.CodeCommit; +import com.amazonaws.services.lambda.runtime.events.CodeCommitEvent.Record; +import com.amazonaws.services.lambda.runtime.events.CodeCommitEvent.Reference; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import java.util.ArrayList; +import java.util.List; // Handler value: example.HandlerCodeCommit -public class HandlerCodeCommit implements RequestHandler{ - Gson gson = new GsonBuilder().setPrettyPrinting().create(); +public class HandlerCodeCommit implements RequestHandler>{ + @Override - public String handleRequest(CodeCommitEvent event, Context context) + public List handleRequest(CodeCommitEvent event, Context context) { LambdaLogger logger = context.getLogger(); - String response = new String("200 OK"); - // log execution details - Util.logEnvironment(event, context, gson); - return response; + logger.log("EVENT TYPE: " + event.getClass().toString()); + var commitsFound = new ArrayList(); + for (Record record : event.getRecords()) { + CodeCommit commit = record.getCodeCommit(); + for (Reference reference : commit.getReferences()) { + commitsFound.add(reference.getCommit()); + } + } + return commitsFound; } } \ No newline at end of file diff --git a/sample-apps/java-events/src/main/java/example/HandlerCognito.java b/sample-apps/java-events/src/main/java/example/HandlerCognito.java index d610356e..c8443c27 100644 --- a/sample-apps/java-events/src/main/java/example/HandlerCognito.java +++ b/sample-apps/java-events/src/main/java/example/HandlerCognito.java @@ -1,23 +1,26 @@ package example; import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.LambdaLogger; +import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.CognitoEvent; +import com.amazonaws.services.lambda.runtime.events.CognitoEvent.DatasetRecord; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import java.util.ArrayList; +import java.util.List; // Handler value: example.HandlerCognito -public class HandlerCognito implements RequestHandler{ - Gson gson = new GsonBuilder().setPrettyPrinting().create(); +public class HandlerCognito implements RequestHandler>{ + @Override - public String handleRequest(CognitoEvent event, Context context) + public List handleRequest(CognitoEvent event, Context context) { LambdaLogger logger = context.getLogger(); - String response = new String("200 OK"); - // log execution details - Util.logEnvironment(event, context, gson); - return response; + logger.log("EVENT TYPE: " + event.getClass().toString()); + var operationsFound = new ArrayList(); + for (DatasetRecord record : event.getDatasetRecords().values()) { + operationsFound.add(record.getOp()); + } + return operationsFound; } } \ No newline at end of file diff --git a/sample-apps/java-events/src/main/java/example/HandlerConfig.java b/sample-apps/java-events/src/main/java/example/HandlerConfig.java index 651a7bf0..9d875333 100644 --- a/sample-apps/java-events/src/main/java/example/HandlerConfig.java +++ b/sample-apps/java-events/src/main/java/example/HandlerConfig.java @@ -1,23 +1,18 @@ package example; import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.LambdaLogger; +import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.ConfigEvent; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - // Handler value: example.HandlerConfig public class HandlerConfig implements RequestHandler{ - Gson gson = new GsonBuilder().setPrettyPrinting().create(); + @Override public String handleRequest(ConfigEvent event, Context context) { LambdaLogger logger = context.getLogger(); - String response = new String("200 OK"); - // log execution details - Util.logEnvironment(event, context, gson); - return response; + logger.log("EVENT TYPE: " + event.getClass().toString()); + return event.getConfigRuleArn(); } } \ No newline at end of file diff --git a/sample-apps/java-events/src/main/java/example/HandlerDynamoDB.java b/sample-apps/java-events/src/main/java/example/HandlerDynamoDB.java new file mode 100644 index 00000000..21b6f222 --- /dev/null +++ b/sample-apps/java-events/src/main/java/example/HandlerDynamoDB.java @@ -0,0 +1,26 @@ +package example; + +import com.amazonaws.services.lambda.runtime.Context; +import com.amazonaws.services.lambda.runtime.LambdaLogger; +import com.amazonaws.services.lambda.runtime.RequestHandler; +import com.amazonaws.services.lambda.runtime.events.DynamodbEvent; +import com.amazonaws.services.lambda.runtime.events.DynamodbEvent.DynamodbStreamRecord; + +import java.util.ArrayList; +import java.util.List; + +// Handler value: example.HandlerDynamoDB +public class HandlerDynamoDB implements RequestHandler>{ + + @Override + public List handleRequest(DynamodbEvent event, Context context) + { + LambdaLogger logger = context.getLogger(); + logger.log("EVENT TYPE: " + event.getClass().toString()); + var operationsFound = new ArrayList(); + for (DynamodbStreamRecord record : event.getRecords()) { + operationsFound.add(record.getEventName()); + } + return operationsFound; + } +} \ No newline at end of file diff --git a/sample-apps/java-events/src/main/java/example/HandlerFirehose.java b/sample-apps/java-events/src/main/java/example/HandlerFirehose.java index 59504e44..988b4f6d 100644 --- a/sample-apps/java-events/src/main/java/example/HandlerFirehose.java +++ b/sample-apps/java-events/src/main/java/example/HandlerFirehose.java @@ -1,23 +1,26 @@ package example; import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.LambdaLogger; +import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.KinesisFirehoseEvent; +import com.amazonaws.services.lambda.runtime.events.KinesisFirehoseEvent.Record; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import java.util.ArrayList; +import java.util.List; // Handler value: example.HandlerFirehose -public class HandlerFirehose implements RequestHandler{ - Gson gson = new GsonBuilder().setPrettyPrinting().create(); +public class HandlerFirehose implements RequestHandler>{ + @Override - public String handleRequest(KinesisFirehoseEvent event, Context context) + public List handleRequest(KinesisFirehoseEvent event, Context context) { LambdaLogger logger = context.getLogger(); - String response = new String("200 OK"); - // log execution details - Util.logEnvironment(event, context, gson); - return response; + logger.log("EVENT TYPE: " + event.getClass().toString()); + var recordIds = new ArrayList(); + for (Record record : event.getRecords()) { + recordIds.add(record.getRecordId()); + } + return recordIds; } } \ No newline at end of file diff --git a/sample-apps/java-events-v1sdk/src/main/java/example/HandlerKinesis.java b/sample-apps/java-events/src/main/java/example/HandlerKinesis.java similarity index 58% rename from sample-apps/java-events-v1sdk/src/main/java/example/HandlerKinesis.java rename to sample-apps/java-events/src/main/java/example/HandlerKinesis.java index c5406b13..cefa78fe 100644 --- a/sample-apps/java-events-v1sdk/src/main/java/example/HandlerKinesis.java +++ b/sample-apps/java-events/src/main/java/example/HandlerKinesis.java @@ -1,32 +1,31 @@ package example; import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.LambdaLogger; +import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.KinesisEvent; import com.amazonaws.services.lambda.runtime.events.KinesisEvent.KinesisEventRecord; -import com.amazonaws.services.kinesis.model.Record; - import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.List; // Handler value: example.HandleKinesis -public class HandlerKinesis implements RequestHandler{ - private static final Logger logger = LoggerFactory.getLogger(HandlerKinesis.class); +public class HandlerKinesis implements RequestHandler>{ + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + @Override - public String handleRequest(KinesisEvent event, Context context) + public List handleRequest(KinesisEvent event, Context context) { - String response = new String("200 OK"); + LambdaLogger logger = context.getLogger(); + logger.log("EVENT TYPE: " + event.getClass().toString()); + var dataRecords = new ArrayList(); for(KinesisEventRecord record : event.getRecords()) { - logger.info(gson.toJson(record.getKinesis().getData())); + dataRecords.add(gson.toJson(record.getKinesis().getData())); } - // log execution details - Util.logEnvironment(event, context, gson); - return response; + return dataRecords; } } \ No newline at end of file diff --git a/sample-apps/java-events/src/main/java/example/HandlerLex.java b/sample-apps/java-events/src/main/java/example/HandlerLex.java index d09f97bd..efb5f71c 100644 --- a/sample-apps/java-events/src/main/java/example/HandlerLex.java +++ b/sample-apps/java-events/src/main/java/example/HandlerLex.java @@ -1,23 +1,18 @@ package example; import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.LambdaLogger; +import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.LexEvent; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - // Handler value: example.HandlerLex public class HandlerLex implements RequestHandler{ - Gson gson = new GsonBuilder().setPrettyPrinting().create(); + @Override public String handleRequest(LexEvent event, Context context) { LambdaLogger logger = context.getLogger(); - String response = new String("200 OK"); - // log execution details - Util.logEnvironment(event, context, gson); - return response; + logger.log("EVENT TYPE: " + event.getClass().toString()); + return event.getCurrentIntent().getName(); } } \ No newline at end of file diff --git a/sample-apps/java-events/src/main/java/example/HandlerS3.java b/sample-apps/java-events/src/main/java/example/HandlerS3.java new file mode 100644 index 00000000..adc96dff --- /dev/null +++ b/sample-apps/java-events/src/main/java/example/HandlerS3.java @@ -0,0 +1,26 @@ +package example; + +import com.amazonaws.services.lambda.runtime.Context; +import com.amazonaws.services.lambda.runtime.LambdaLogger; +import com.amazonaws.services.lambda.runtime.RequestHandler; +import com.amazonaws.services.lambda.runtime.events.S3Event; +import com.amazonaws.services.lambda.runtime.events.models.s3.S3EventNotification.S3EventNotificationRecord; + +// Handler value: example.Handler +public class HandlerS3 implements RequestHandler{ + + @Override + public String handleRequest(S3Event event, Context context) + { + LambdaLogger logger = context.getLogger(); + S3EventNotificationRecord record = event.getRecords().get(0); + String srcBucket = record.getS3().getBucket().getName(); + // Object key may have spaces or unicode non-ASCII characters. + String srcKey = record.getS3().getObject().getUrlDecodedKey(); + logger.log("RECORD: " + record); + logger.log("SOURCE BUCKET: " + srcBucket); + logger.log("SOURCE KEY: " + srcKey); + // log execution details + return srcBucket + "/" + srcKey; + } +} \ No newline at end of file diff --git a/sample-apps/java-events/src/main/java/example/HandlerSNS.java b/sample-apps/java-events/src/main/java/example/HandlerSNS.java index 977ae82a..6b0aa666 100644 --- a/sample-apps/java-events/src/main/java/example/HandlerSNS.java +++ b/sample-apps/java-events/src/main/java/example/HandlerSNS.java @@ -1,23 +1,28 @@ package example; import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.LambdaLogger; +import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.SNSEvent; +import com.amazonaws.services.lambda.runtime.events.SNSEvent.SNS; +import com.amazonaws.services.lambda.runtime.events.SNSEvent.SNSRecord; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import java.util.ArrayList; +import java.util.List; // Handler value: example.HandlerSNS -public class HandlerSNS implements RequestHandler{ - Gson gson = new GsonBuilder().setPrettyPrinting().create(); +public class HandlerSNS implements RequestHandler>{ + @Override - public String handleRequest(SNSEvent event, Context context) + public List handleRequest(SNSEvent event, Context context) { LambdaLogger logger = context.getLogger(); - String response = new String("200 OK"); - // log execution details - Util.logEnvironment(event, context, gson); - return response; + logger.log("EVENT TYPE: " + event.getClass().toString()); + var messagesFound = new ArrayList(); + for (SNSRecord record : event.getRecords()) { + SNS message = record.getSNS(); + messagesFound.add(message.getMessage()); + } + return messagesFound; } } \ No newline at end of file diff --git a/sample-apps/java-events/src/main/java/example/HandlerSQS.java b/sample-apps/java-events/src/main/java/example/HandlerSQS.java new file mode 100644 index 00000000..dabb49a2 --- /dev/null +++ b/sample-apps/java-events/src/main/java/example/HandlerSQS.java @@ -0,0 +1,26 @@ +package example; + +import com.amazonaws.services.lambda.runtime.Context; +import com.amazonaws.services.lambda.runtime.LambdaLogger; +import com.amazonaws.services.lambda.runtime.RequestHandler; +import com.amazonaws.services.lambda.runtime.events.SQSEvent; +import com.amazonaws.services.lambda.runtime.events.SQSEvent.SQSMessage; + +import java.util.ArrayList; +import java.util.List; + +// Handler value: example.HandlerSQS +public class HandlerSQS implements RequestHandler>{ + + @Override + public List handleRequest(SQSEvent event, Context context) + { + LambdaLogger logger = context.getLogger(); + logger.log("EVENT TYPE: " + event.getClass().toString()); + var messagesFound = new ArrayList(); + for(SQSMessage msg : event.getRecords()){ + messagesFound.add(msg.getBody()); + } + return messagesFound; + } +} diff --git a/sample-apps/java-events/src/main/java/example/Util.java b/sample-apps/java-events/src/main/java/example/Util.java deleted file mode 100644 index b5e87294..00000000 --- a/sample-apps/java-events/src/main/java/example/Util.java +++ /dev/null @@ -1,20 +0,0 @@ -package example; - -import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.LambdaLogger; - -import com.google.gson.Gson; - -public class Util { - - public static void logEnvironment(Object event, Context context, Gson gson) - { - LambdaLogger logger = context.getLogger(); - // log execution details - logger.log("ENVIRONMENT VARIABLES: " + gson.toJson(System.getenv())); - logger.log("CONTEXT: " + gson.toJson(context)); - // log event details - logger.log("EVENT: " + gson.toJson(event)); - logger.log("EVENT TYPE: " + event.getClass().toString()); - } -} \ No newline at end of file diff --git a/sample-apps/java-events/src/test/java/example/InvokeTest.java b/sample-apps/java-events/src/test/java/example/InvokeTest.java index cb7d949a..881519cc 100644 --- a/sample-apps/java-events/src/test/java/example/InvokeTest.java +++ b/sample-apps/java-events/src/test/java/example/InvokeTest.java @@ -1,33 +1,205 @@ package example; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertNotNull; import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; -import com.amazonaws.services.lambda.runtime.events.APIGatewayV2ProxyRequestEvent; -import com.amazonaws.services.lambda.runtime.events.APIGatewayV2ProxyResponseEvent; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; +import com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPEvent; +import com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPResponse; +import com.amazonaws.services.lambda.runtime.events.CloudFrontEvent; +import com.amazonaws.services.lambda.runtime.events.CloudWatchLogsEvent; +import com.amazonaws.services.lambda.runtime.events.CodeCommitEvent; +import com.amazonaws.services.lambda.runtime.events.CognitoEvent; +import com.amazonaws.services.lambda.runtime.events.ConfigEvent; +import com.amazonaws.services.lambda.runtime.events.DynamodbEvent; +import com.amazonaws.services.lambda.runtime.events.KinesisEvent; +import com.amazonaws.services.lambda.runtime.events.KinesisFirehoseEvent; +import com.amazonaws.services.lambda.runtime.events.LexEvent; +import com.amazonaws.services.lambda.runtime.events.S3Event; +import com.amazonaws.services.lambda.runtime.events.SNSEvent; +import com.amazonaws.services.lambda.runtime.events.SQSEvent; +import com.amazonaws.services.lambda.runtime.events.ScheduledEvent; +import com.amazonaws.services.lambda.runtime.tests.annotations.Event; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import java.util.List; + +import org.junit.jupiter.params.ParameterizedTest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.List; -import java.util.ArrayList; -import java.util.HashMap; - class InvokeTest { + private static final Logger logger = LoggerFactory.getLogger(InvokeTest.class); + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + + @ParameterizedTest + @Event(value = "events/apigateway-v1.json", type = APIGatewayProxyRequestEvent.class) + void testApiGatewayV1(APIGatewayProxyRequestEvent event) { + logger.info("Invoke TEST - ApiGatewayV1"); + Context context = new TestContext(); + HandlerApiGatewayV1 handler = new HandlerApiGatewayV1(); + APIGatewayProxyResponseEvent response = handler.handleRequest(event, context); + String expected = "" + "Hello world!" + "" + + "

Welcome

Page generated by a Lambda function.

" + + ""; + assertEquals(expected, response.getBody()); + } + + @ParameterizedTest + @Event(value = "events/apigateway-v2.json", type = APIGatewayV2HTTPEvent.class) + void testApiGatewayV2(APIGatewayV2HTTPEvent event) { + logger.info("Invoke TEST - ApiGatewayV1"); + Context context = new TestContext(); + HandlerApiGatewayV2 handler = new HandlerApiGatewayV2(); + APIGatewayV2HTTPResponse response = handler.handleRequest(event, context); + String expected = "" + "Hello world!" + "" + + "

Welcome

Page generated by a Lambda function.

" + + ""; + assertEquals(expected, response.getBody()); + } + + @ParameterizedTest + @Event(value = "events/cloudfront.json", type = CloudFrontEvent.class) + void testCloudFront(CloudFrontEvent event) { + logger.info("Invoke TEST - CloudFront"); + Context context = new TestContext(); + HandlerCloudFront handler = new HandlerCloudFront(); + List response = handler.handleRequest(event, context); + assertEquals(1, response.size()); + assertEquals("/picture.jpg", response.get(0)); + } + + @ParameterizedTest + @Event(value = "events/codecommit-push.json", type = CodeCommitEvent.class) + void testCodeCommit(CodeCommitEvent event) { + logger.info("Invoke TEST - CodeCommit"); + Context context = new TestContext(); + HandlerCodeCommit handler = new HandlerCodeCommit(); + List response = handler.handleRequest(event, context); + assertEquals(1, response.size()); + assertEquals("5c4ef1049f1d27deadbeeff313e0730018be182b", response.get(0)); + } + + @ParameterizedTest + @Event(value = "events/cognito-sync.json", type = CognitoEvent.class) + void testCognito(CognitoEvent event) { + logger.info("Invoke TEST - Cognito"); + Context context = new TestContext(); + HandlerCognito handler = new HandlerCognito(); + List response = handler.handleRequest(event, context); + assertEquals(2, response.size()); + assertEquals("replace", response.get(0)); + assertEquals("replace", response.get(1)); + } + + @ParameterizedTest + @Event(value = "events/config-rule.json", type = ConfigEvent.class) + void testConfig(ConfigEvent event) { + logger.info("Invoke TEST - Config"); + Context context = new TestContext(); + HandlerConfig handler = new HandlerConfig(); + String response = handler.handleRequest(event, context); + assertEquals("arn:aws:config:ca-central-1:123456789012:config-rule/config-rule-0123456", response); + } - @Test - void invokeTest() { - logger.info("Invoke TEST"); - APIGatewayV2ProxyRequestEvent event = new APIGatewayV2ProxyRequestEvent(); + @ParameterizedTest + @Event(value = "events/cloudwatch-scheduled.json", type = ScheduledEvent.class) + void testCWEvents(ScheduledEvent event) { + logger.info("Invoke TEST - CWEvents"); Context context = new TestContext(); - String requestId = context.getAwsRequestId(); - Handler handler = new Handler(); - APIGatewayV2ProxyResponseEvent result = handler.handleRequest(event, context); - assertEquals(result.getStatusCode(),200); + HandlerCWEvents handler = new HandlerCWEvents(); + List response = handler.handleRequest(event, context); + assertEquals(1, response.size()); + assertEquals("arn:aws:events:us-east-2:123456789012:rule/my-rule", response.get(0)); } + @ParameterizedTest + @Event(value = "events/cloudwatch-logs.json", type = CloudWatchLogsEvent.class) + void testCWLogs(CloudWatchLogsEvent event) { + logger.info("Invoke TEST - CWLogs"); + Context context = new TestContext(); + HandlerCWLogs handler = new HandlerCWLogs(); + String response = handler.handleRequest(event, context); + assertNotNull(response); + } + + @ParameterizedTest + @Event(value = "events/dynamodb-record.json", type = DynamodbEvent.class) + void testDynamoDB(DynamodbEvent event) { + logger.info("Invoke TEST - DynamoDB"); + Context context = new TestContext(); + HandlerDynamoDB handler = new HandlerDynamoDB(); + List response = handler.handleRequest(event, context); + assertEquals(2, response.size()); + assertEquals("INSERT", response.get(0)); + assertEquals("MODIFY", response.get(1)); + } + + @ParameterizedTest + @Event(value = "events/firehose-record.json", type = KinesisFirehoseEvent.class) + void testFirehose(KinesisFirehoseEvent event) { + logger.info("Invoke TEST - Firehose"); + Context context = new TestContext(); + HandlerFirehose handler = new HandlerFirehose(); + List response = handler.handleRequest(event, context); + assertEquals(1, response.size()); + assertEquals("49546986683135544286507457936321625675700192471156785154", response.get(0)); + } + + @ParameterizedTest + @Event(value = "events/kinesis-record.json", type = KinesisEvent.class) + void testKinesis(KinesisEvent event) { + logger.info("Invoke TEST - Kinesis"); + Context context = new TestContext(); + HandlerKinesis handler = new HandlerKinesis(); + List response = handler.handleRequest(event, context); + assertEquals(2, response.size()); + } + + @ParameterizedTest + @Event(value = "events/lex-flowers.json", type = LexEvent.class) + void testLex(LexEvent event) { + logger.info("Invoke TEST - Lex"); + Context context = new TestContext(); + HandlerLex handler = new HandlerLex(); + String response = handler.handleRequest(event, context); + assertEquals("OrderFlowers", response); + } + + @ParameterizedTest + @Event(value = "events/s3-notification.json", type = S3Event.class) + void testS3(S3Event event) { + logger.info("Invoke TEST - S3"); + Context context = new TestContext(); + HandlerS3 handler = new HandlerS3(); + String response = handler.handleRequest(event, context); + assertEquals("BUCKET_NAME/inbound/sample-java-s3.png", response); + } + + @ParameterizedTest + @Event(value = "events/sns-notification.json", type = SNSEvent.class) + void testSNS(SNSEvent event) { + logger.info("Invoke TEST - SNS"); + Context context = new TestContext(); + HandlerSNS handler = new HandlerSNS(); + List response = handler.handleRequest(event, context); + assertEquals(1, response.size()); + assertEquals("Updated and expanded documentation for using Lambda with API Gateway, including support for HTTP APIs.", response.get(0)); + } + + @ParameterizedTest + @Event(value = "events/sqs-record.json", type = SQSEvent.class) + void testSQS(SQSEvent event) { + logger.info("Invoke TEST - SQS"); + Context context = new TestContext(); + HandlerSQS handler = new HandlerSQS(); + List response = handler.handleRequest(event, context); + assertEquals(1, response.size()); + assertEquals("Hello from SQS!", response.get(0)); + } } diff --git a/sample-apps/java-events/template-mvn.yml b/sample-apps/java-events/template-mvn.yml index 5fdfbe50..1e17bcbd 100644 --- a/sample-apps/java-events/template-mvn.yml +++ b/sample-apps/java-events/template-mvn.yml @@ -6,15 +6,15 @@ Resources: Type: AWS::Serverless::Function Properties: CodeUri: target/java-events-1.0-SNAPSHOT.jar - Handler: example.Handler - Runtime: java8 + Handler: example.HandlerSQS + Runtime: java11 Description: Java function - MemorySize: 512 + MemorySize: 2048 Timeout: 10 # Function's execution role Policies: - AWSLambdaBasicExecutionRole - - AWSLambdaReadOnlyAccess + - AWSLambda_ReadOnlyAccess - AWSXrayWriteOnlyAccess - AWSLambdaVPCAccessExecutionRole Tracing: Active diff --git a/sample-apps/java-events/template.yml b/sample-apps/java-events/template.yml index def7925a..4b8bb3d8 100644 --- a/sample-apps/java-events/template.yml +++ b/sample-apps/java-events/template.yml @@ -6,15 +6,15 @@ Resources: Type: AWS::Serverless::Function Properties: CodeUri: build/distributions/java-events.zip - Handler: example.Handler - Runtime: java8 + Handler: example.HandlerSQS + Runtime: java11 Description: Java function - MemorySize: 512 + MemorySize: 2048 Timeout: 10 # Function's execution role Policies: - AWSLambdaBasicExecutionRole - - AWSLambdaReadOnlyAccess + - AWSLambda_ReadOnlyAccess - AWSXrayWriteOnlyAccess - AWSLambdaVPCAccessExecutionRole Tracing: Active diff --git a/sample-apps/layer-java/function/pom.xml b/sample-apps/layer-java/function/pom.xml new file mode 100644 index 00000000..607f4152 --- /dev/null +++ b/sample-apps/layer-java/function/pom.xml @@ -0,0 +1,59 @@ + + 4.0.0 + com.example + layer-java-function + jar + 1.0-SNAPSHOT + layer-java-function + + + UTF-8 + 21 + 21 + + + + + com.example + layer-java-layer + 1.0-SNAPSHOT + provided + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.13.0 + + 21 + 21 + 21 + + + + + + + \ No newline at end of file diff --git a/sample-apps/layer-java/function/src/main/java/example/F1Car.java b/sample-apps/layer-java/function/src/main/java/example/F1Car.java new file mode 100644 index 00000000..06c77d22 --- /dev/null +++ b/sample-apps/layer-java/function/src/main/java/example/F1Car.java @@ -0,0 +1,33 @@ +package example; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class F1Car { + + private String team; + private String driver; + + @JsonCreator + public F1Car(@JsonProperty("team") String team, + @JsonProperty("driver") String driver) { + this.team = team; + this.driver = driver; + } + + public String getTeam() { + return team; + } + + public void setTeam(String team) { + this.team = team; + } + + public String getDriver() { + return driver; + } + + public void setDriver(String driver) { + this.driver = driver; + } +} diff --git a/sample-apps/layer-java/function/src/main/java/example/Handler.java b/sample-apps/layer-java/function/src/main/java/example/Handler.java new file mode 100644 index 00000000..1ff1c4e9 --- /dev/null +++ b/sample-apps/layer-java/function/src/main/java/example/Handler.java @@ -0,0 +1,22 @@ +package example; + +import com.amazonaws.services.lambda.runtime.Context; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.IOException; +import java.util.Map; + +public class Handler { + + public String handleRequest(Map input, Context context) throws IOException { + // Parse the input JSON + ObjectMapper objectMapper = new ObjectMapper(); + F1Car f1Car = objectMapper.readValue(objectMapper.writeValueAsString(input), F1Car.class); + + StringBuilder finalString = new StringBuilder(); + finalString.append(f1Car.getDriver()); + finalString.append(" is a driver for team "); + finalString.append(f1Car.getTeam()); + return finalString.toString(); + } +} diff --git a/sample-apps/layer-java/layer/1-install.sh b/sample-apps/layer-java/layer/1-install.sh new file mode 100755 index 00000000..b39292ee --- /dev/null +++ b/sample-apps/layer-java/layer/1-install.sh @@ -0,0 +1 @@ +mvn clean install diff --git a/sample-apps/layer-java/layer/2-package.sh b/sample-apps/layer-java/layer/2-package.sh new file mode 100755 index 00000000..f7a9c67b --- /dev/null +++ b/sample-apps/layer-java/layer/2-package.sh @@ -0,0 +1,4 @@ +mkdir java +mkdir java/lib +cp -r target/layer-java-layer-1.0-SNAPSHOT.jar java/lib/ +zip -r layer_content.zip java diff --git a/sample-apps/layer-java/layer/pom.xml b/sample-apps/layer-java/layer/pom.xml new file mode 100644 index 00000000..ccfc9025 --- /dev/null +++ b/sample-apps/layer-java/layer/pom.xml @@ -0,0 +1,62 @@ + + 4.0.0 + com.example + layer-java-layer + jar + 1.0-SNAPSHOT + layer-java-layer + + + UTF-8 + 21 + 21 + + + + + com.amazonaws + aws-lambda-java-core + 1.2.3 + + + + com.fasterxml.jackson.core + jackson-databind + 2.17.0 + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.13.0 + + 21 + 21 + 21 + + + + + org.apache.maven.plugins + maven-shade-plugin + 3.5.2 + + false + + + + package + + shade + + + + + + + + \ No newline at end of file diff --git a/sample-apps/layer-nodejs/function-js/index.mjs b/sample-apps/layer-nodejs/function-js/index.mjs new file mode 100644 index 00000000..d94c925c --- /dev/null +++ b/sample-apps/layer-nodejs/function-js/index.mjs @@ -0,0 +1,17 @@ +import _ from "lodash" + +export const handler = async (event) => { + + var users = [ + { 'user': 'Carlos', 'active': true }, + { 'user': 'Gil-dong', 'active': false }, + { 'user': 'Pat', 'active': false } + ]; + + let out = _.findLastIndex(users, function(o) { return o.user == 'Pat'; }); + const response = { + statusCode: 200, + body: JSON.stringify(out + ", " + users[out].user), + }; + return response; +}; diff --git a/sample-apps/layer-nodejs/function-ts/index.ts b/sample-apps/layer-nodejs/function-ts/index.ts new file mode 100644 index 00000000..83ecea6e --- /dev/null +++ b/sample-apps/layer-nodejs/function-ts/index.ts @@ -0,0 +1,28 @@ +import { Handler } from 'aws-lambda'; +import * as _ from 'lodash'; + +type User = { + user: string; + active: boolean; +} + +type UserResult = { + statusCode: number; + body: string; +} + +const users: User[] = [ + { 'user': 'Carlos', 'active': true }, + { 'user': 'Gil-dong', 'active': false }, + { 'user': 'Pat', 'active': false } +]; + +export const handler: Handler = async (): Promise => { + + let out = _.findLastIndex(users, (user: User) => { return user.user == 'Pat'; }); + const response = { + statusCode: 200, + body: JSON.stringify(out + ", " + users[out].user), + }; + return response; +}; diff --git a/sample-apps/layer-nodejs/function-ts/package.json b/sample-apps/layer-nodejs/function-ts/package.json new file mode 100644 index 00000000..1857273d --- /dev/null +++ b/sample-apps/layer-nodejs/function-ts/package.json @@ -0,0 +1,20 @@ +{ + "name": "lambda-typescript-layer-example", + "version": "1.0.0", + "main": "dist/index.js", + "scripts": { + "prebuild": "rm -rf dist", + "build": "tsc index.ts --module nodenext --lib es2020 --outDir dist/", + "postbuild": "cd dist && zip -r index.zip index.js", + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "", + "license": "MIT-0", + "description": "", + "devDependencies": { + "@types/aws-lambda": "^8.10.145", + "@types/lodash": "^4.17.9", + "lodash": "^4.17.21", + "typescript": "^5.6.2" + } +} diff --git a/sample-apps/layer-nodejs/layer/1-install.sh b/sample-apps/layer-nodejs/layer/1-install.sh new file mode 100755 index 00000000..9c3be6f5 --- /dev/null +++ b/sample-apps/layer-nodejs/layer/1-install.sh @@ -0,0 +1 @@ +npm install . diff --git a/sample-apps/layer-nodejs/layer/2-package.sh b/sample-apps/layer-nodejs/layer/2-package.sh new file mode 100755 index 00000000..e8a5defc --- /dev/null +++ b/sample-apps/layer-nodejs/layer/2-package.sh @@ -0,0 +1,3 @@ +mkdir -p nodejs/node20 +cp -r node_modules nodejs/node20/ +zip -r layer_content.zip nodejs diff --git a/sample-apps/layer-nodejs/layer/package.json b/sample-apps/layer-nodejs/layer/package.json new file mode 100644 index 00000000..d2229f35 --- /dev/null +++ b/sample-apps/layer-nodejs/layer/package.json @@ -0,0 +1,14 @@ +{ + "name": "layer", + "version": "1.0.0", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "", + "license": "MIT-0", + "description": "", + "dependencies": { + "lodash": "4.17.21" + } +} diff --git a/sample-apps/layer-python/function-numpy/lambda_function.py b/sample-apps/layer-python/function-numpy/lambda_function.py new file mode 100644 index 00000000..f245743f --- /dev/null +++ b/sample-apps/layer-python/function-numpy/lambda_function.py @@ -0,0 +1,12 @@ +import json +import numpy as np + +def lambda_handler(event, context): + + x = np.arange(15, dtype=np.int64).reshape(3, 5) + print(x) + + return { + 'statusCode': 200, + 'body': json.dumps('Hello from Lambda!') + } diff --git a/sample-apps/layer-python/function/lambda_function.py b/sample-apps/layer-python/function/lambda_function.py new file mode 100644 index 00000000..11ef4b5e --- /dev/null +++ b/sample-apps/layer-python/function/lambda_function.py @@ -0,0 +1,9 @@ +import requests + +def lambda_handler(event, context): + print(f"Version of requests library: {requests.__version__}") + request = requests.get('https://api.github.com/') + return { + 'statusCode': request.status_code, + 'body': request.text + } diff --git a/sample-apps/layer-python/layer-numpy/1-install.sh b/sample-apps/layer-python/layer-numpy/1-install.sh new file mode 100755 index 00000000..43172827 --- /dev/null +++ b/sample-apps/layer-python/layer-numpy/1-install.sh @@ -0,0 +1,3 @@ +python3.11 -m venv create_layer +source create_layer/bin/activate +pip install -r requirements.txt --platform=manylinux2014_x86_64 --only-binary=:all: --target ./create_layer/lib/python3.11/site-packages diff --git a/sample-apps/layer-python/layer-numpy/2-package.sh b/sample-apps/layer-python/layer-numpy/2-package.sh new file mode 100755 index 00000000..e552d783 --- /dev/null +++ b/sample-apps/layer-python/layer-numpy/2-package.sh @@ -0,0 +1,3 @@ +mkdir python +cp -r create_layer/lib python/ +zip -r layer_content.zip python \ No newline at end of file diff --git a/sample-apps/layer-python/layer-numpy/requirements.txt b/sample-apps/layer-python/layer-numpy/requirements.txt new file mode 100644 index 00000000..d4db0621 --- /dev/null +++ b/sample-apps/layer-python/layer-numpy/requirements.txt @@ -0,0 +1 @@ +https://files.pythonhosted.org/packages/3a/d0/edc009c27b406c4f9cbc79274d6e46d634d139075492ad055e3d68445925/numpy-1.26.4-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl diff --git a/sample-apps/layer-python/layer/1-install.sh b/sample-apps/layer-python/layer/1-install.sh new file mode 100755 index 00000000..c9d93b81 --- /dev/null +++ b/sample-apps/layer-python/layer/1-install.sh @@ -0,0 +1,3 @@ +python3.13 -m venv create_layer +source create_layer/bin/activate +pip install -r requirements.txt diff --git a/sample-apps/layer-python/layer/2-package.sh b/sample-apps/layer-python/layer/2-package.sh new file mode 100755 index 00000000..b720b012 --- /dev/null +++ b/sample-apps/layer-python/layer/2-package.sh @@ -0,0 +1,3 @@ +mkdir python +cp -r create_layer/lib python/ +zip -r layer_content.zip python diff --git a/sample-apps/layer-python/layer/requirements.txt b/sample-apps/layer-python/layer/requirements.txt new file mode 100644 index 00000000..2c24336e --- /dev/null +++ b/sample-apps/layer-python/layer/requirements.txt @@ -0,0 +1 @@ +requests==2.31.0 diff --git a/sample-apps/layer-ruby/function/lambda_function.rb b/sample-apps/layer-ruby/function/lambda_function.rb new file mode 100644 index 00000000..2c6d85d3 --- /dev/null +++ b/sample-apps/layer-ruby/function/lambda_function.rb @@ -0,0 +1,8 @@ +require 'json' +require 'tzinfo' + +def lambda_handler(event:, context:) + tz = TZInfo::Timezone.get('America/New_York') + { statusCode: 200, body: tz.to_local(Time.utc(2018, 2, 1, 12, 30, 0)) } +end + diff --git a/sample-apps/layer-ruby/layer/1-install.sh b/sample-apps/layer-ruby/layer/1-install.sh new file mode 100755 index 00000000..eaf29ac1 --- /dev/null +++ b/sample-apps/layer-ruby/layer/1-install.sh @@ -0,0 +1,3 @@ +bundle config set --local path 'vendor/bundle' +bundle install + diff --git a/sample-apps/layer-ruby/layer/2-package.sh b/sample-apps/layer-ruby/layer/2-package.sh new file mode 100755 index 00000000..305a5b7b --- /dev/null +++ b/sample-apps/layer-ruby/layer/2-package.sh @@ -0,0 +1,3 @@ +mkdir -p ruby/gems/3.3.0 +cp -r vendor/bundle/ruby/3.3.0/* ruby/gems/3.3.0/ +zip -r layer_content.zip ruby diff --git a/sample-apps/layer-ruby/layer/Gemfile b/sample-apps/layer-ruby/layer/Gemfile new file mode 100644 index 00000000..64ad6202 --- /dev/null +++ b/sample-apps/layer-ruby/layer/Gemfile @@ -0,0 +1,5 @@ +# frozen_string_literal: true + +source "https://rubygems.org" + +gem "tzinfo" diff --git a/sample-apps/list-manager/1-create-bucket.sh b/sample-apps/list-manager/1-create-bucket.sh deleted file mode 100755 index 042ebe32..00000000 --- a/sample-apps/list-manager/1-create-bucket.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/bash -set -eo pipefail -BUCKET_ID=$(dd if=/dev/random bs=8 count=1 2>/dev/null | od -An -tx1 | tr -d ' \t\n') -BUCKET_NAME=lambda-artifacts-$BUCKET_ID -echo $BUCKET_NAME > bucket-name.txt -aws s3 mb s3://$BUCKET_NAME diff --git a/sample-apps/list-manager/2-create-dbpasswordsecret.sh b/sample-apps/list-manager/2-create-dbpasswordsecret.sh deleted file mode 100755 index 10e3f236..00000000 --- a/sample-apps/list-manager/2-create-dbpasswordsecret.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/bash -set -eo pipefail -DB_PASSWORD=$(dd if=/dev/random bs=8 count=1 2>/dev/null | od -An -tx1 | tr -d ' \t\n') -aws secretsmanager create-secret --name list-manager --description "List-manager database password" --secret-string "{\"password\":\"$DB_PASSWORD\"}" diff --git a/sample-apps/list-manager/3-deploy-vpc.sh b/sample-apps/list-manager/3-deploy-vpc.sh deleted file mode 100755 index 69360e53..00000000 --- a/sample-apps/list-manager/3-deploy-vpc.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/bash -set -eo pipefail -aws cloudformation deploy --template-file template-vpcrds.yml --stack-name list-manager-vpc diff --git a/sample-apps/list-manager/4-deploy.sh b/sample-apps/list-manager/4-deploy.sh deleted file mode 100755 index 599b815c..00000000 --- a/sample-apps/list-manager/4-deploy.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/bash -set -eo pipefail -ARTIFACT_BUCKET=$(cat bucket-name.txt) -cd lib/nodejs && npm install && cd ../../ -aws cloudformation package --template-file template.yml --s3-bucket $ARTIFACT_BUCKET --output-template-file out.yml -aws cloudformation deploy --template-file out.yml --stack-name list-manager --capabilities CAPABILITY_NAMED_IAM diff --git a/sample-apps/list-manager/5-create-dbtable.sh b/sample-apps/list-manager/5-create-dbtable.sh deleted file mode 100755 index 213be7fb..00000000 --- a/sample-apps/list-manager/5-create-dbtable.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/bash -set -eo pipefail -FUNCTION=$(aws cloudformation describe-stack-resource --stack-name list-manager --logical-resource-id dbadmin --query 'StackResourceDetail.PhysicalResourceId' --output text) -aws lambda invoke --function-name $FUNCTION --payload file://events/db-create-table.json out.json diff --git a/sample-apps/list-manager/6-invoke.sh b/sample-apps/list-manager/6-invoke.sh deleted file mode 100755 index 5d507a48..00000000 --- a/sample-apps/list-manager/6-invoke.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/bash -set -eo pipefail -FUNCTION=$(aws cloudformation describe-stack-resource --stack-name list-manager --logical-resource-id processor --query 'StackResourceDetail.PhysicalResourceId' --output text) - -while true; do - aws lambda invoke --function-name $FUNCTION --payload file://events/kinesis.json out.json - cat out.json - echo "" - sleep 2 -done diff --git a/sample-apps/list-manager/7-put-records.sh b/sample-apps/list-manager/7-put-records.sh deleted file mode 100755 index bdd7637b..00000000 --- a/sample-apps/list-manager/7-put-records.sh +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/bash -set -eo pipefail -STREAM=$(aws cloudformation describe-stack-resource --stack-name list-manager --logical-resource-id stream --query 'StackResourceDetail.PhysicalResourceId' --output text) -aws kinesis put-record --stream-name $STREAM --data '{"title": "favorite movies", "user": "rdlysct", "type": "rank", "entries": {"blade runner": 2, "the empire strikes back": 3, "alien": 1}}' --partition-key 0 -aws kinesis put-record --stream-name $STREAM --data '{"title": "stats", "user": "beth", "type": "tally", "entries": {"xp": 25}}' --partition-key 0 -aws kinesis put-record --stream-name $STREAM --data '{"title": "favorite movies", "user": "mike", "type": "rank", "entries": {"blade runner": 1, "the empire strikes back": 2, "alien": 3}}' --partition-key 0 -aws kinesis put-record --stream-name $STREAM --data '{"title": "stats", "user": "bill", "type": "tally", "entries": {"xp": 83}}' --partition-key 0 \ No newline at end of file diff --git a/sample-apps/list-manager/8-cleanup.sh b/sample-apps/list-manager/8-cleanup.sh deleted file mode 100755 index 2dcc1ae6..00000000 --- a/sample-apps/list-manager/8-cleanup.sh +++ /dev/null @@ -1,38 +0,0 @@ -#!/bin/bash -set -eo pipefail -STACK=list-manager -if [[ $# -eq 1 ]] ; then - STACK=$1 - echo "Deleting stack $STACK" -fi -FUNCTION=$(aws cloudformation describe-stack-resource --stack-name $STACK --logical-resource-id function --query 'StackResourceDetail.PhysicalResourceId' --output text) -aws cloudformation delete-stack --stack-name $STACK -echo "Deleted $STACK stack." - -if [ -f bucket-name.txt ]; then - ARTIFACT_BUCKET=$(cat bucket-name.txt) - if [[ ! $ARTIFACT_BUCKET =~ lambda-artifacts-[a-z0-9]{16} ]] ; then - echo "Bucket was not created by this application. Skipping." - else - while true; do - read -p "Delete deployment artifacts and bucket ($ARTIFACT_BUCKET)? (y/n)" response - case $response in - [Yy]* ) aws s3 rb --force s3://$ARTIFACT_BUCKET; rm bucket-name.txt; break;; - [Nn]* ) break;; - * ) echo "Response must start with y or n.";; - esac - done - fi -fi - -while true; do - read -p "Delete function log group (/aws/lambda/$FUNCTION)? (y/n)" response - case $response in - [Yy]* ) aws logs delete-log-group --log-group-name /aws/lambda/$FUNCTION; break;; - [Nn]* ) break;; - * ) echo "Response must start with y or n.";; - esac -done - -rm out.yml out.json -rm -rf lib/nodejs/node_modules \ No newline at end of file diff --git a/sample-apps/list-manager/README.md b/sample-apps/list-manager/README.md deleted file mode 100644 index fee53bb2..00000000 --- a/sample-apps/list-manager/README.md +++ /dev/null @@ -1,221 +0,0 @@ -# Processing a Kinesis stream with database resources in a VPC - -This sample application processes records from an Amazon Kinesis stream to create and update lists. It uses a private VPC to connect to an Amazon Relational Database Service (Amazon RDS) database. It uses a VPC endpoint to connect to Amazon DynamoDB. The application also uses AWS Secrets Manager, AWS X-Ray, and AWS CodeDeploy. - -![Architecture](/sample-apps/list-manager/images/sample-listmanager.png) - -The processor function doesn't read directly from the Kinesis stream. Instead, an AWS Lambda event source mapping reads records from the Kinesis stream and sends them to the processor function in batches. The processor function stores all incoming events in a MySQL database, and maintains the current state of each list in a DynamoDB table. - -The project source includes function code and supporting resources: - -- `processor` - A Node.js function that processes records from a Kinesis stream. -- `dbadmin` - A Node.js function that runs SQL commands for administrator use. -- `lib` - A Lambda layer with the npm modules used by the application's functions. -- `events` - JSON documents that can be used to test the application's functions. -- `template.yml` - An AWS CloudFormation template that creates the application. -- `template-vpcrds.yml` - A template that creates the VPC and Amazon RDS database instance. -- `1-create-bucket.sh`, `2-create-dbpasswordsecret.sh`, and other scripts - Shell scripts that use the AWS CLI to deploy and manage the application. -- `bin` - Additional scripts. - -The processor supports the following types of lists: - -## Ranking - -A list of names with a rank or weight. For example: - - - Top 10 lists - Integer values 1-N. - - Weighted rankings - Any number values. - -Rankings are combined into an aggregate list. When a user updates their ranking, the change (added, removed, and moved entries) is applied to the aggregate list as well. - -## Stats - -A list of fields to increment. For example: - - - Expenses - Amounts spent on gasoline, meals out, and so on. - - Character state - Stats such as health, experience points, and steps walked. - -# Requirements - -To deploy the sample application, you need the following tools: - -- [Node.js 10 with npm](https://nodejs.org/en/download/releases/). -- The Bash shell. For Linux and macOS, this is included by default. In Windows 10, you can install the [Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows-integrated version of Ubuntu and Bash. -- [The AWS CLI v1](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html). - -To run the sample application in AWS, you need permission to use Lambda and the following services: - -- Amazon RDS ([pricing](https://aws.amazon.com/rds/pricing/)) -- Amazon Kinesis ([pricing](https://aws.amazon.com/kinesis/pricing/)) -- Amazon DynamoDB ([pricing](https://aws.amazon.com/dynamodb/pricing/)) -- Amazon VPC ([pricing](https://aws.amazon.com/vpc/pricing/)) -- AWS Secrets Manager ([pricing](https://aws.amazon.com/secrets-manager/pricing/)) -- AWS CodeDeploy ([pricing](https://aws.amazon.com/codedeploy/pricing/)) -- AWS X-Ray ([pricing](https://aws.amazon.com/xray/pricing/)) -- AWS Identity and Access Management -- AWS CloudFormation - -Standard charges apply for each service. - -# Setup - -Download or clone this repository. - - $ git clone https://github.com/awsdocs/aws-lambda-developer-guide.git - $ cd aws-lambda-developer-guide/sample-apps/list-manager - -To create a new bucket for deployment artifacts, run `1-create-bucket.sh`. - - list-manager$ ./1-create-bucket.sh - make_bucket: lambda-artifacts-a5e491dbb5b22e0d - -To create a database password and store it in AWS Secrets Manager, run the `2-create-dbpasswordsecret.sh` script. - - list-manager$ ./2-create-dbpasswordsecret.sh - -To create the VPC and RDS database instance, run the `3-deploy-vpc.sh` script. This process takes about 15 minutes. - - list-manager$ ./3-deploy-vpc.sh - -# Deploy - -To deploy the application, run `4-deploy.sh`. - - list-manager$ ./4-deploy.sh - Uploading to e678bc216e6a0d510d661ca9ae2fd941 2678 / 2678.0 (100.00%) - Successfully packaged artifacts and wrote output template to file out.yml. - Waiting for changeset to be created.. - Waiting for stack create/update to complete - Successfully created/updated stack - list-manager - -This script uses AWS CloudFormation to deploy the Lambda functions and an IAM role. If the AWS CloudFormation stack that contains the resources already exists, the script updates it with any changes to the template or function code. - -To create a table in the database, run the `5-create-dbtable.sh` script. - - list-manager$ ./5-create-dbtable.sh - -# Test - -To invoke the function with a test event, run `6-invoke.sh`. - - list-manager$ ./6-invoke.sh - { - "StatusCode": 200, - "ExecutedVersion": "$LATEST" - } - -Let the script invoke the function a few times and then press `CRTL+C` to exit. - -If that succeeds, send records to the Kinesis stream. The processor function's event source mapping pulls records from the stream and invokes the function. - - list-manager$ ./7-put-records.sh - -The application uses AWS X-Ray to trace requests. Open the [X-Ray console](https://console.aws.amazon.com/xray/home#/service-map) to view the service map. The following service map shows the function writing to the two DynamoDB tables and the MySQL database. - -![Service Map](/sample-apps/list-manager/images/listmanager-servicemap.png) - -Choose a node in the main function graph. Then choose **View traces** to see a list of traces. Choose any trace to view a timeline that breaks down the work done by the function. - -![Trace](/sample-apps/list-manager/images/listmanager-trace.png) - -Finally, view the application in the Lambda console. - -*To view the application* -1. Open the [applications page](https://console.aws.amazon.com/lambda/home#/applications) in the Lambda console. -2. Choose **list-manager**. - - ![Application](/sample-apps/list-manager/images/listmanager-application.png) - -# Kinesis record structure - -Tally list: - - { - "title": "stats", - "type": "tally", - "user": "andy", - "entries": [ - "xp": 20 - ] - } - -Rank list: - - { - "title": "favorite movie", - "type": "rank", - "user": "andy", - "entries": [ - "blade runner": 1, - "the empire strikes back": 2 - "alien": 3 - ] - } - -# Table structure - -Per-user table: - - { - "id": "#12AB", - "aggid": "#12AB", - "title": "stats", - "type": "tally", - "last updated": 1234567890123, - "user": "andy" - "entries": [ - { - "xp": 100 - } - ] - } - - { - "id": "#12AB", - "aggid": "#12AB", - "title": "stats", - "type": "rank", - "last updated": 1234567890123, - "user": "andy" - "entries": [ - { - "blade runner": 1, - "the empire strikes back": 2, - "alien": 3 - } - ] - } - -Aggregate table: - - { - "id": "#12AB", - "title": "stats", - "type": "tally", - "last updated": 1234567890123, - "entries": [ - { - "xp": 500 - } - ] - } - - { - "id": "#12AB", - "title": "favorite movie", - "type": "rank", - "last updated": 1234567890123, - "entries": [ - { - "blade runner": 3, - "the empire strikes back": 5, - "alien": 4 - } - ] - } - -# Cleanup - -To delete the application, run the cleanup script. - - list-manager$ ./8-cleanup.sh diff --git a/sample-apps/list-manager/bin/get-kinesis-stream.sh b/sample-apps/list-manager/bin/get-kinesis-stream.sh deleted file mode 100755 index 8f7cebe4..00000000 --- a/sample-apps/list-manager/bin/get-kinesis-stream.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/bash -set -eo pipefail -STREAM=$(aws cloudformation describe-stack-resource --stack-name list-manager --logical-resource-id stream --query 'StackResourceDetail.PhysicalResourceId' --output text) -echo $STREAM diff --git a/sample-apps/list-manager/bin/get-stack-event.sh b/sample-apps/list-manager/bin/get-stack-event.sh deleted file mode 100755 index 57e468b7..00000000 --- a/sample-apps/list-manager/bin/get-stack-event.sh +++ /dev/null @@ -1 +0,0 @@ -aws cloudformation describe-stack-events --stack-name list-manager --max-items 1 --query 'StackEvents[0]' diff --git a/sample-apps/list-manager/bin/get-stack-status.sh b/sample-apps/list-manager/bin/get-stack-status.sh deleted file mode 100755 index 1f8b2b5d..00000000 --- a/sample-apps/list-manager/bin/get-stack-status.sh +++ /dev/null @@ -1 +0,0 @@ -aws cloudformation describe-stacks --stack-name list-manager --query 'Stacks[*].StackStatus' --output text diff --git a/sample-apps/list-manager/dbadmin/index.js b/sample-apps/list-manager/dbadmin/index.js deleted file mode 100644 index b0309956..00000000 --- a/sample-apps/list-manager/dbadmin/index.js +++ /dev/null @@ -1,37 +0,0 @@ -var AWSXRay = require('aws-xray-sdk-core') -var captureMySQL = require('aws-xray-sdk-mysql') -var mysql = captureMySQL(require('mysql')) -const username = process.env.databaseUser -const password = process.env.databasePassword -const host = process.env.databaseHost - -exports.handler = async (event) => { - var connection = mysql.createConnection({ - host : host, - user : username, - password : password, - database : 'lambdadb' - }) - var query = event.query - var result - connection.connect() - - connection.query(query, function (error, results, fields) { - if (error) throw error - console.log("Ran query: " + query) - for (result in results) - console.log(results[result]) - }) - - return new Promise( ( resolve, reject ) => { - connection.end( err => { - if ( err ) - return reject( err ) - const response = { - statusCode: 200, - body: JSON.stringify(result), - } - resolve(response) - }) - }) -} diff --git a/sample-apps/list-manager/dbadmin/package.json b/sample-apps/list-manager/dbadmin/package.json deleted file mode 100644 index 774c74cf..00000000 --- a/sample-apps/list-manager/dbadmin/package.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "list-manager-processor", - "version": "1.0.0", - "private": true, - "dependencies": {}, - "devDependencies": { - "aws-xray-sdk-core": "2.4.0", - "aws-xray-sdk-mysql": "2.4.0", - "mysql": "2.17.1" - }, - "scripts": {} -} diff --git a/sample-apps/list-manager/events/db-clear-table.json b/sample-apps/list-manager/events/db-clear-table.json deleted file mode 100644 index 1cad4eb0..00000000 --- a/sample-apps/list-manager/events/db-clear-table.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "query": "DELETE FROM events" -} \ No newline at end of file diff --git a/sample-apps/list-manager/events/db-create-table.json b/sample-apps/list-manager/events/db-create-table.json deleted file mode 100644 index 9698225c..00000000 --- a/sample-apps/list-manager/events/db-create-table.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "query": "CREATE TABLE events ( id varchar(255), title varchar(255), timestamp BIGINT, entries varchar(32765));" -} \ No newline at end of file diff --git a/sample-apps/list-manager/events/db-read-table.json b/sample-apps/list-manager/events/db-read-table.json deleted file mode 100644 index 2b0ece0b..00000000 --- a/sample-apps/list-manager/events/db-read-table.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "query": "SELECT * FROM events" -} \ No newline at end of file diff --git a/sample-apps/list-manager/events/kinesis.json b/sample-apps/list-manager/events/kinesis.json deleted file mode 100644 index 1960433c..00000000 --- a/sample-apps/list-manager/events/kinesis.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "Records": [ - { - "kinesis": { - "kinesisSchemaVersion": "1.0", - "partitionKey": "0", - "sequenceNumber": "49598630142999655949899443842509554952738656579378741250", - "data": "eyJ0aXRsZSI6ICJmYXZvcml0ZSBtb3ZpZXMiLCAidXNlciI6ICJyZGx5c2N0IiwgInR5cGUiOiAicmFuayIsICJlbnRyaWVzIjogeyJibGFkZSBydW5uZXIiOiAyLCAidGhlIGVtcGlyZSBzdHJpa2VzIGJhY2siOiAzLCAiYWxpZW4iOiAxfX0=", - "approximateArrivalTimestamp": 1570667770.615 - }, - "eventSource": "aws:kinesis", - "eventVersion": "1.0", - "eventID": "shardId-000000000000:49598630142999655949899443842509554952738656579378741250", - "eventName": "aws:kinesis:record", - "invokeIdentityArn": "arn:aws:iam::123456789012:role/list-manager-processorRole-7FYXMPLH7IUS", - "awsRegion": "us-east-2", - "eventSourceARN": "arn:aws:kinesis:us-east-2:123456789012:stream/list-manager-stream-87B3XMPLF1AZ" - }, - { - "kinesis": { - "kinesisSchemaVersion": "1.0", - "partitionKey": "0", - "sequenceNumber": "49598630142999655949899443843117644640004815122975424514", - "data": "eyJ0aXRsZSI6ICJzdGF0cyIsICJ1c2VyIjogImJldGgiLCAidHlwZSI6ICJ0YWxseSIsICJlbnRyaWVzIjogeyJ4cCI6IDI1fX0=", - "approximateArrivalTimestamp": 1570667771.753 - }, - "eventSource": "aws:kinesis", - "eventVersion": "1.0", - "eventID": "shardId-000000000000:49598630142999655949899443843117644640004815122975424514", - "eventName": "aws:kinesis:record", - "invokeIdentityArn": "arn:aws:iam::123456789012:role/list-manager-processorRole-7FYXMPLH7IUS", - "awsRegion": "us-east-2", - "eventSourceARN": "arn:aws:kinesis:us-east-2:123456789012:stream/list-manager-stream-87B3XMPLF1AZ" - }, - { - "kinesis": { - "kinesisSchemaVersion": "1.0", - "partitionKey": "0", - "sequenceNumber": "49598630142999655949899443123457048701043305532981510146", - "data": "eyJ0aXRsZSI6ICJmYXZvcml0ZSBtb3ZpZXMiLCAidXNlciI6ICJtaWtlIiwgInR5cGUiOiAicmFuayIsICJlbnRyaWVzIjogeyJibGFkZSBydW5uZXIiOiAxLCAidGhlIGVtcGlyZSBzdHJpa2VzIGJhY2siOiAyLCAiYWxpZW4iOiAzfX0=", - "approximateArrivalTimestamp": 1570667772.81 - }, - "eventSource": "aws:kinesis", - "eventVersion": "1.0", - "eventID": "shardId-000000000000:49598630142999655949899443123457048701043305532981510146", - "eventName": "aws:kinesis:record", - "invokeIdentityArn": "arn:aws:iam::123456789012:role/list-manager-processorRole-7FYXMPLH7IUS", - "awsRegion": "us-east-2", - "eventSourceARN": "arn:aws:kinesis:us-east-2:123456789012:stream/list-manager-stream-87B3XMPLF1AZ" - }, - { - "kinesis": { - "kinesisSchemaVersion": "1.0", - "partitionKey": "0", - "sequenceNumber": "49598630142999655949899443844127097699383030621294034946", - "data": "eyJ0aXRsZSI6ICJzdGF0cyIsICJ1c2VyIjogImJpbGwiLCAidHlwZSI6ICJ0YWxseSIsICJlbnRyaWVzIjogeyJ4cCI6IDgzfX0=", - "approximateArrivalTimestamp": 1570667773.832 - }, - "eventSource": "aws:kinesis", - "eventVersion": "1.0", - "eventID": "shardId-000000000000:49598630142999655949899443844127097699383030621294034946", - "eventName": "aws:kinesis:record", - "invokeIdentityArn": "arn:aws:iam::123456789012:role/list-manager-processorRole-7FYXMPLH7IUS", - "awsRegion": "us-east-2", - "eventSourceARN": "arn:aws:kinesis:us-east-2:123456789012:stream/list-manager-stream-87B3XMPLF1AZ" - } - ] -} \ No newline at end of file diff --git a/sample-apps/list-manager/images/listmanager-application.png b/sample-apps/list-manager/images/listmanager-application.png deleted file mode 100644 index 86521f33..00000000 Binary files a/sample-apps/list-manager/images/listmanager-application.png and /dev/null differ diff --git a/sample-apps/list-manager/images/listmanager-servicemap.png b/sample-apps/list-manager/images/listmanager-servicemap.png deleted file mode 100644 index 34dff816..00000000 Binary files a/sample-apps/list-manager/images/listmanager-servicemap.png and /dev/null differ diff --git a/sample-apps/list-manager/images/listmanager-trace.png b/sample-apps/list-manager/images/listmanager-trace.png deleted file mode 100644 index fc2e86c9..00000000 Binary files a/sample-apps/list-manager/images/listmanager-trace.png and /dev/null differ diff --git a/sample-apps/list-manager/images/sample-listmanager.png b/sample-apps/list-manager/images/sample-listmanager.png deleted file mode 100644 index e21efebd..00000000 Binary files a/sample-apps/list-manager/images/sample-listmanager.png and /dev/null differ diff --git a/sample-apps/list-manager/lib/nodejs/package.json b/sample-apps/list-manager/lib/nodejs/package.json deleted file mode 100644 index f5859d75..00000000 --- a/sample-apps/list-manager/lib/nodejs/package.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "lib-layer", - "version": "1.0.0", - "private": true, - "dependencies": { - "aws-xray-sdk-core": "2.4.0", - "aws-xray-sdk-mysql": "2.4.0", - "md5": "2.2.1", - "mysql": "2.17.1" - }, - "scripts": {} -} diff --git a/sample-apps/list-manager/processor/index.js b/sample-apps/list-manager/processor/index.js deleted file mode 100644 index 540a6104..00000000 --- a/sample-apps/list-manager/processor/index.js +++ /dev/null @@ -1,170 +0,0 @@ -// AWS X-Ray SDK -var AWSXRay = require('aws-xray-sdk-core') -var captureMySQL = require('aws-xray-sdk-mysql') -var mysql = captureMySQL(require('mysql')) -// AWS SDK clients -// NOTE: Function needs permission for each service in execution role -var AWS = AWSXRay.captureAWS(require('aws-sdk')) -// Create client outside of handler to reuse -var docClient = new AWS.DynamoDB.DocumentClient() -var md5 = require('md5') -// Read bucket name from environment variable -const table = process.env.table -const aggtable = process.env.aggtable -const username = process.env.databaseUser -const password = process.env.databasePassword -const host = process.env.databaseHost -const dbtable = "events" - -// Use Amazon DynamoDB client -var updateList = async function(event){ - // shallow copy of event - let item = { ... event } - // aggregate ID (all entries with same title) - item.aggid = md5(item.title) - // individual ID (from same user only) - item.id = md5(item.title + item.user) - // TODO: check for existing documents - // get agg item - var aggdata = await docClient.get({TableName:aggtable, Key: { id: item.aggid }}).promise() - console.log("AGGDATA: " + JSON.stringify(aggdata, null, 2)) - - // get indv item - var data = await docClient.get({TableName:table, Key: { id: item.id, aggid: item.aggid }}).promise() - console.log("DATA: " + JSON.stringify(data, null, 2)) - - var newEntries = JSON.parse(event.entries) - var oldEntries = {} - var aggItem = {} - if (data.Item) - oldEntries = JSON.parse(data.Item.entries) - var aggregateEntries = {} - if (aggdata.Item) { - aggregateEntries = JSON.parse(aggdata.Item.entries) - aggItem = aggdata.Item - } else { - aggItem.id = item.aggid - aggItem.title = item.title - aggItem.type = item.type - aggItem['last updated'] = item.timestamp - } - // TODO: store contributor user IDs in aggregate item and confirm their presence before applying delta - var deltaEntries = newEntries - console.log("NEW ENTRIES: " + JSON.stringify(newEntries, null, 2)) - console.log("OLD ENTRIES: " + JSON.stringify(oldEntries, null, 2)) - if ( event.type == "rank" ) { - // calculate changes vs existing indv list - Object.keys(newEntries).forEach(function(key,index) { - if (oldEntries.hasOwnProperty(key)) - deltaEntries[key] -= oldEntries[key] - }) - Object.keys(oldEntries).forEach(function(key,index) { - if (!newEntries.hasOwnProperty(key)) - deltaEntries[key] = -oldEntries[key] - }) - // update aggregate list - Object.keys(deltaEntries).forEach(function(key,index) { - if (aggregateEntries.hasOwnProperty(key)) - aggregateEntries[key] += deltaEntries[key] - else - aggregateEntries[key] = newEntries[key] - }) - } - if ( event.type == "tally" ) { - // update existing indv list - Object.keys(newEntries).forEach(function(key,index) { - //TODO: check type of value = number - if (oldEntries.hasOwnProperty(key)) - oldEntries[key] += newEntries[key] - else - oldEntries[key] = newEntries[key] - }) - Object.keys(deltaEntries).forEach(function(key,index) { - if (aggregateEntries.hasOwnProperty(key)) - aggregateEntries[key] += deltaEntries[key] - else - aggregateEntries[key] = newEntries[key] - }) - item.entries = JSON.stringify(oldEntries, null, 0) - console.log("TALLIED ENTRIES: " + item.entries) - } - console.log("DELTA ENTRIES: " + JSON.stringify(deltaEntries, null, 0)) - item['last updated'] = item.timestamp - delete item.timestamp - - var params = { - TableName: table, - Item: item - } - - await docClient.put(params).promise() - - aggItem.entries = JSON.stringify(aggregateEntries, null, 0) - console.log("AGGREGATE ENTRIES: " + aggItem.entries) - - params.Item = aggItem - params.TableName = aggtable - await docClient.put(params).promise() - -} - -// Use mysql client -var storeEvent = async function(event, connection){ - // update database - var query = "INSERT INTO " + dbtable + " (id, title, timestamp, entries) VALUES ?;" - var values = [[event.id, event.title, event.timestamp, event.entries]] - console.log("storing event:") - console.log(event.id + "," + event.title + "," + event.timestamp + "," + event.entries) - return new Promise( ( resolve, reject ) => { - connection.query(query, [values], function (error, results, fields) { - if (error) - return reject(error) - resolve(results) - }) - }) -} - -var processRecords = async function(records, connection) { - for (const record of records) { - // Decode kinesis data - const data = Buffer.from(record.kinesis.data, 'base64').toString('ascii') - var event = {} - const item = JSON.parse(data) - event.title = item.title - event.user = item.user - event.type = item.type - event.entries = JSON.stringify(item.entries, null, 0) - event.id = record.eventID - event.timestamp = record.kinesis.approximateArrivalTimestamp * 1000 - console.log("EVENT TIMESTAMP:" + event.timestamp) - // update table - await updateList(event) - await storeEvent(event, connection) - } -} - -exports.handler = async function(kinesisEvent, context) { - console.log("EVENT\n" + JSON.stringify(kinesisEvent, null, 2)) - var connection = mysql.createConnection({ - host : host, - user : username, - password : password, - database : 'lambdadb' - }) - console.log("connecting to db") - connection.connect() - var result - // process event - await processRecords(kinesisEvent.Records, connection) - return new Promise( ( resolve, reject ) => { - connection.end( err => { - if ( err ) - return reject( err ) - const response = { - statusCode: 200, - body: JSON.stringify(result), - } - resolve(response) - } ) - } ) -} \ No newline at end of file diff --git a/sample-apps/list-manager/processor/package.json b/sample-apps/list-manager/processor/package.json deleted file mode 100644 index 1428d7bd..00000000 --- a/sample-apps/list-manager/processor/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "list-manager-processor", - "version": "1.0.0", - "private": true, - "dependencies": {}, - "devDependencies": { - "aws-sdk": "2.488.0", - "aws-xray-sdk-core": "2.4.0", - "aws-xray-sdk-mysql": "2.4.0", - "md5": "2.2.1", - "mysql": "2.17.1" - }, - "scripts": {} -} diff --git a/sample-apps/list-manager/template-vpcrds.yml b/sample-apps/list-manager/template-vpcrds.yml deleted file mode 100644 index a60a3fcf..00000000 --- a/sample-apps/list-manager/template-vpcrds.yml +++ /dev/null @@ -1,157 +0,0 @@ -AWSTemplateFormatVersion: 2010-09-09 -Parameters: - databaseName: - Default: lambdadb - Description: Database name - Type: String - MinLength: '1' - MaxLength: '64' - AllowedPattern: '[a-zA-Z][a-zA-Z0-9]*' - ConstraintDescription: Begin with a letter and use only alphanumeric characters. - databaseUser: - NoEcho: 'true' - Description: Database username - Default: admin - Type: String - MinLength: '1' - MaxLength: '16' - AllowedPattern: '[a-zA-Z][a-zA-Z0-9]*' - ConstraintDescription: Begin with a letter and use only alphanumeric characters. -Resources: - databaseSubnetGroup: - Type: AWS::RDS::DBSubnetGroup - Properties: - DBSubnetGroupDescription: Subnets - SubnetIds: - - !Ref privateSubnetA - - !Ref privateSubnetB - database: - Type: AWS::RDS::DBInstance - Properties: - DBName: !Ref databaseName - AllocatedStorage: '10' - DBInstanceClass: db.t3.small - Engine: MySQL - EngineVersion: 8.0.15 - MasterUsername: !Ref 'databaseUser' - MasterUserPassword: '{{resolve:secretsmanager:list-manager:SecretString:password}}' - DeletionProtection: true - MultiAZ: true - DBSubnetGroupName: !Ref databaseSubnetGroup - VPCSecurityGroups: - - !GetAtt privateVPC.DefaultSecurityGroup - privateVPC: - Type: AWS::EC2::VPC - Properties: - CidrBlock: 172.31.0.0/16 - Tags: - - Key: Name - Value: !Ref AWS::StackName - privateSubnetA: - Type: AWS::EC2::Subnet - Properties: - VpcId: !Ref privateVPC - AvailabilityZone: - Fn::Select: - - 0 - - Fn::GetAZs: "" - CidrBlock: 172.31.3.0/24 - MapPublicIpOnLaunch: false - Tags: - - Key: Name - Value: !Join ["-", [!Ref "AWS::StackName","subnet-a"]] - privateSubnetB: - Type: AWS::EC2::Subnet - Properties: - VpcId: !Ref privateVPC - AvailabilityZone: - Fn::Select: - - 1 - - Fn::GetAZs: "" - CidrBlock: 172.31.2.0/24 - MapPublicIpOnLaunch: false - Tags: - - Key: Name - Value: !Join ["-", [!Ref "AWS::StackName","subnet-b"]] - privateRouteTable: - Type: AWS::EC2::RouteTable - Properties: - VpcId: !Ref privateVPC - privateSubnetARouteTableAssociation: - Type: AWS::EC2::SubnetRouteTableAssociation - Properties: - SubnetId: !Ref privateSubnetA - RouteTableId: !Ref privateRouteTable - privateSubnetBRouteTableAssociation: - Type: AWS::EC2::SubnetRouteTableAssociation - Properties: - SubnetId: !Ref privateSubnetB - RouteTableId: !Ref privateRouteTable - s3Endpoint: - Type: AWS::EC2::VPCEndpoint - Properties: - PolicyDocument: - Version: 2012-10-17 - Statement: - - Effect: Allow - Principal: "*" - Action: - - "s3:*" - Resource: - - "*" - RouteTableIds: - - !Ref privateRouteTable - ServiceName: !Sub com.amazonaws.${AWS::Region}.s3 - VpcId: !Ref privateVPC - dynamoDBEndpoint: - Type: AWS::EC2::VPCEndpoint - Properties: - PolicyDocument: - Version: 2012-10-17 - Statement: - - Effect: Allow - Principal: "*" - Action: - - "dynamodb:*" - Resource: - - "*" - RouteTableIds: - - !Ref privateRouteTable - ServiceName: !Sub com.amazonaws.${AWS::Region}.dynamodb - VpcId: !Ref privateVPC -Outputs: - privateVPCSecurityGroup: - Description: Default security for Lambda VPC - Value: !GetAtt privateVPC.DefaultSecurityGroup - Export: - Name: !Join ["-", [!Ref "AWS::StackName","vpc-sg"]] - privateVPCID: - Description: VPC ID - Value: !Ref privateVPC - Export: - Name: !Join ["-", [!Ref "AWS::StackName","vpc"]] - privateSubnetAID: - Description: Private Subnet A ID - Value: !Ref privateSubnetA - Export: - Name: !Join ["-", [!Ref "AWS::StackName","subnet-a"]] - privateSubnetBID: - Description: Private Subnet B ID - Value: !Ref privateSubnetB - Export: - Name: !Join ["-", [!Ref "AWS::StackName","subnet-b"]] - databaseHost: - Description: Database hostname - Value: !GetAtt database.Endpoint.Address - Export: - Name: !Join ["-", [!Ref "AWS::StackName","db-host"]] - databaseName: - Description: Database name - Value: !Ref databaseName - Export: - Name: !Join ["-", [!Ref "AWS::StackName","db-name"]] - databaseUser: - Description: Database user - Value: !Ref databaseUser - Export: - Name: !Join ["-", [!Ref "AWS::StackName","db-user"]] diff --git a/sample-apps/list-manager/template.yml b/sample-apps/list-manager/template.yml deleted file mode 100644 index 215bdcc3..00000000 --- a/sample-apps/list-manager/template.yml +++ /dev/null @@ -1,125 +0,0 @@ -AWSTemplateFormatVersion: 2010-09-09 -Description: An AWS Lambda application that uses Amazon Kinesis and Amazon RDS. -Transform: AWS::Serverless-2016-10-31 -Parameters: - vpcStackName: - Default: list-manager-vpc - Description: VPC and database stack name - Type: String -Globals: - Function: - Runtime: nodejs12.x - Tracing: Active - Handler: index.handler - AutoPublishAlias: live - Environment: - Variables: - table: !Ref table - aggtable: !Ref aggtable - databaseHost: - Fn::ImportValue: - !Sub "${vpcStackName}-db-host" - databaseName: - Fn::ImportValue: - !Sub "${vpcStackName}-db-name" - databaseUser: - Fn::ImportValue: - !Sub "${vpcStackName}-db-user" - databasePassword: '{{resolve:secretsmanager:list-manager:SecretString:password}}' - VpcConfig: - SecurityGroupIds: - - Fn::ImportValue: - !Sub "${vpcStackName}-vpc-sg" - SubnetIds: - - Fn::ImportValue: - !Sub "${vpcStackName}-subnet-a" - - Fn::ImportValue: - !Sub "${vpcStackName}-subnet-b" - DeploymentPreference: - Type: AllAtOnce - Role: !GetAtt deployrole.Arn - Layers: - - !Ref libs -Resources: - deployrole: - Type: AWS::IAM::Role - Properties: - AssumeRolePolicyDocument: - Version: "2012-10-17" - Statement: - - Effect: Allow - Principal: - Service: - - codedeploy.amazonaws.com - Action: - - sts:AssumeRole - ManagedPolicyArns: - - arn:aws:iam::aws:policy/service-role/AWSCodeDeployRoleForLambda - libs: - Type: AWS::Serverless::LayerVersion - Properties: - LayerName: list-manager-lib - Description: Dependencies for the list manager sample app. - ContentUri: lib/. - CompatibleRuntimes: - - nodejs12.x - dbadmin: - Type: AWS::Serverless::Function - Properties: - CodeUri: dbadmin/. - Description: Run SQL queries. - MemorySize: 128 - Timeout: 15 - # Function's execution role - Policies: - - AWSLambdaBasicExecutionRole - - AWSLambdaVPCAccessExecutionRole - processor: - Type: AWS::Serverless::Function - Properties: - CodeUri: processor/. - Description: Process events from Amazon Kinesis - MemorySize: 128 - Timeout: 100 - # Function's execution role - Policies: - - AWSLambdaBasicExecutionRole - - AWSLambdaKinesisExecutionRole - - AmazonDynamoDBFullAccess - - AWSLambdaVPCAccessExecutionRole - Events: - kinesis: - Type: Kinesis - Properties: - Stream: !GetAtt stream.Arn - BatchSize: 100 - StartingPosition: LATEST - stream: - Type: AWS::Kinesis::Stream - Properties: - ShardCount: 1 - table: - Type: AWS::DynamoDB::Table - Properties: - AttributeDefinitions: - - AttributeName: "id" - AttributeType: "S" - - AttributeName: "aggid" - AttributeType: "S" - KeySchema: - - AttributeName: "aggid" - KeyType: "HASH" - - AttributeName: "id" - KeyType: "RANGE" - ProvisionedThroughput: - ReadCapacityUnits: "2" - WriteCapacityUnits: "2" - aggtable: - Type: AWS::Serverless::SimpleTable - Properties: - PrimaryKey: - Name: id - Type: String - ProvisionedThroughput: - ReadCapacityUnits: 2 - WriteCapacityUnits: 2 diff --git a/sample-apps/nodejs-apig/3-invoke.sh b/sample-apps/nodejs-apig/3-invoke.sh index a5c32b1d..7838da23 100755 --- a/sample-apps/nodejs-apig/3-invoke.sh +++ b/sample-apps/nodejs-apig/3-invoke.sh @@ -3,7 +3,7 @@ set -eo pipefail FUNCTION=$(aws cloudformation describe-stack-resource --stack-name nodejs-apig --logical-resource-id function --query 'StackResourceDetail.PhysicalResourceId' --output text) while true; do - aws lambda invoke --function-name $FUNCTION --payload file://event.json out.json + aws lambda invoke --function-name $FUNCTION --payload fileb://event.json out.json cat out.json echo "" sleep 2 diff --git a/sample-apps/nodejs-apig/README.md b/sample-apps/nodejs-apig/README.md index 15e689e4..cc3681b3 100644 --- a/sample-apps/nodejs-apig/README.md +++ b/sample-apps/nodejs-apig/README.md @@ -15,9 +15,9 @@ The project source includes function code and supporting resources: Use the following instructions to deploy the sample application. # Requirements -- [Node.js 10 with npm](https://nodejs.org/en/download/releases/) +- [Node.js 18 with npm](https://nodejs.org/en/download/releases/) - The Bash shell. For Linux and macOS, this is included by default. In Windows 10, you can install the [Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows-integrated version of Ubuntu and Bash. -- [The AWS CLI v1](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html). +- [The AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html) v1.17 or newer. # Setup Download or clone this repository. diff --git a/sample-apps/nodejs-apig/function/index.js b/sample-apps/nodejs-apig/function/index.mjs similarity index 82% rename from sample-apps/nodejs-apig/function/index.js rename to sample-apps/nodejs-apig/function/index.mjs index 3d5fe80a..db6019ff 100644 --- a/sample-apps/nodejs-apig/function/index.js +++ b/sample-apps/nodejs-apig/function/index.mjs @@ -1,14 +1,14 @@ -const AWS = require('aws-sdk') +import {LambdaClient, GetAccountSettingsCommand} from '@aws-sdk/client-lambda'; // Create client outside of handler to reuse -const lambda = new AWS.Lambda() +const lambda = new LambdaClient() // Handler -exports.handler = async function(event, context) { +export const handler = async (event, context) => { console.log('## ENVIRONMENT VARIABLES: ' + serialize(process.env)) console.log('## CONTEXT: ' + serialize(context)) console.log('## EVENT: ' + serialize(event)) try { - let accountSettings = await getAccountSettings() + let accountSettings = await lambda.send(new GetAccountSettingsCommand()) return formatResponse(serialize(accountSettings.AccountUsage)) } catch(error) { return formatError(error) diff --git a/sample-apps/nodejs-apig/package.json b/sample-apps/nodejs-apig/package.json index 271c8428..efb1ca11 100644 --- a/sample-apps/nodejs-apig/package.json +++ b/sample-apps/nodejs-apig/package.json @@ -3,6 +3,6 @@ "version": "1.0.0", "private": true, "devDependencies": { - "aws-sdk": "2.631.0" + "aws-sdk": "2.814.0" } } diff --git a/sample-apps/nodejs-apig/template.yml b/sample-apps/nodejs-apig/template.yml index 8b2d575f..e01993f3 100644 --- a/sample-apps/nodejs-apig/template.yml +++ b/sample-apps/nodejs-apig/template.yml @@ -12,14 +12,14 @@ Resources: Type: AWS::Serverless::Function Properties: Handler: index.handler - Runtime: nodejs12.x + Runtime: nodejs22.x CodeUri: function/. Description: Call the AWS Lambda API Timeout: 10 # Function's execution role Policies: - AWSLambdaBasicExecutionRole - - AWSLambdaReadOnlyAccess + - AWSLambda_ReadOnlyAccess - AWSXrayWriteOnlyAccess Tracing: Active Events: diff --git a/sample-apps/rds-mysql/1-create-bucket.sh b/sample-apps/rds-mysql/1-create-bucket.sh deleted file mode 100755 index 55a9a5a3..00000000 --- a/sample-apps/rds-mysql/1-create-bucket.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/bash -set -eo pipefail -BUCKET_ID=$(dd if=/dev/random bs=8 count=1 2>/dev/null | od -An -tx1 | tr -d ' \t\n') -BUCKET_NAME=lambda-artifacts-$BUCKET_ID -echo $BUCKET_NAME > bucket-name.txt -aws s3 mb s3://$BUCKET_NAME \ No newline at end of file diff --git a/sample-apps/rds-mysql/2-create-dbpasswordsecret.sh b/sample-apps/rds-mysql/2-create-dbpasswordsecret.sh deleted file mode 100755 index 2767bfcd..00000000 --- a/sample-apps/rds-mysql/2-create-dbpasswordsecret.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/bash -set -eo pipefail -DB_PASSWORD=$(dd if=/dev/random bs=8 count=1 2>/dev/null | od -An -tx1 | tr -d ' \t\n') -aws secretsmanager create-secret --name rds-mysql-admin --description "database password" --secret-string "{\"username\":\"admin\",\"password\":\"$DB_PASSWORD\"}" diff --git a/sample-apps/rds-mysql/3-deploy-vpc.sh b/sample-apps/rds-mysql/3-deploy-vpc.sh deleted file mode 100755 index 3c867769..00000000 --- a/sample-apps/rds-mysql/3-deploy-vpc.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/bash -set -eo pipefail -aws cloudformation deploy --template-file template-vpcrds.yml --stack-name rds-mysql-vpc diff --git a/sample-apps/rds-mysql/4-deploy.sh b/sample-apps/rds-mysql/4-deploy.sh deleted file mode 100755 index 1ccc03a5..00000000 --- a/sample-apps/rds-mysql/4-deploy.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/bash -set -eo pipefail -ARTIFACT_BUCKET=$(cat bucket-name.txt) -STACK=rds-mysql -if [[ $# -eq 1 ]] ; then - STACK=$1 - echo "Deploying to stack $STACK" -fi -cd lib/nodejs && npm install && cd ../../ -aws cloudformation package --template-file template.yml --s3-bucket $ARTIFACT_BUCKET --output-template-file out.yml -aws cloudformation deploy --template-file out.yml --stack-name $STACK --capabilities CAPABILITY_NAMED_IAM - -# attach to different VPC -#aws cloudformation deploy --template-file out.yml --stack-name $STACK --capabilities CAPABILITY_NAMED_IAM --parameter-overrides vpcStackName=lambda-vpc secretName=lambda-db-password \ No newline at end of file diff --git a/sample-apps/rds-mysql/5-create-dbtable.sh b/sample-apps/rds-mysql/5-create-dbtable.sh deleted file mode 100755 index 30f97776..00000000 --- a/sample-apps/rds-mysql/5-create-dbtable.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/bash -set -eo pipefail -FUNCTION=$(aws cloudformation describe-stack-resource --stack-name rds-mysql --logical-resource-id dbadmin --query 'StackResourceDetail.PhysicalResourceId' --output text) -aws lambda invoke --function-name $FUNCTION --payload file://events/db-create-table.json out.json diff --git a/sample-apps/rds-mysql/6-invoke.sh b/sample-apps/rds-mysql/6-invoke.sh deleted file mode 100755 index 73a0b68a..00000000 --- a/sample-apps/rds-mysql/6-invoke.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/bash -set -eo pipefail -FUNCTION=$(aws cloudformation describe-stack-resource --stack-name rds-mysql --logical-resource-id dbadmin --query 'StackResourceDetail.PhysicalResourceId' --output text) - -while true; do - aws lambda invoke --function-name $FUNCTION --payload file://events/db-read-table.json out.json - cat out.json - echo "" - sleep 2 -done diff --git a/sample-apps/rds-mysql/7-cleanup.sh b/sample-apps/rds-mysql/7-cleanup.sh deleted file mode 100755 index c35d2a7b..00000000 --- a/sample-apps/rds-mysql/7-cleanup.sh +++ /dev/null @@ -1,38 +0,0 @@ -#!/bin/bash -set -eo pipefail -STACK=rds-mysql -if [[ $# -eq 1 ]] ; then - STACK=$1 - echo "Deleting stack $STACK" -fi -FUNCTION=$(aws cloudformation describe-stack-resource --stack-name $STACK --logical-resource-id function --query 'StackResourceDetail.PhysicalResourceId' --output text) -aws cloudformation delete-stack --stack-name $STACK -echo "Deleted $STACK stack." - -if [ -f bucket-name.txt ]; then - ARTIFACT_BUCKET=$(cat bucket-name.txt) - if [[ ! $ARTIFACT_BUCKET =~ lambda-artifacts-[a-z0-9]{16} ]] ; then - echo "Bucket was not created by this application. Skipping." - else - while true; do - read -p "Delete deployment artifacts and bucket ($ARTIFACT_BUCKET)? (y/n)" response - case $response in - [Yy]* ) aws s3 rb --force s3://$ARTIFACT_BUCKET; rm bucket-name.txt; break;; - [Nn]* ) break;; - * ) echo "Response must start with y or n.";; - esac - done - fi -fi - -while true; do - read -p "Delete function log group (/aws/lambda/$FUNCTION)? (y/n)" response - case $response in - [Yy]* ) aws logs delete-log-group --log-group-name /aws/lambda/$FUNCTION; break;; - [Nn]* ) break;; - * ) echo "Response must start with y or n.";; - esac -done - -rm -f out.yml out.json lib/nodejs/package-lock.json -rm -rf lib/nodejs/node_modules diff --git a/sample-apps/rds-mysql/README.md b/sample-apps/rds-mysql/README.md deleted file mode 100644 index b6d413c4..00000000 --- a/sample-apps/rds-mysql/README.md +++ /dev/null @@ -1,117 +0,0 @@ -# Managing a MySQL for RDS Database in a private VPC - -This sample application runs SQL queries on a MySQL database. It uses a private VPC to connect to an Amazon Relational Database Service (Amazon RDS) database. The application also uses AWS Secrets Manager and AWS X-Ray. - -![Architecture](/sample-apps/rds-mysql/images/sample-rdsmysql.png) - -The function takes a event with the following structure: - -``` -{ - "query": "CREATE TABLE events ( id varchar(255), title varchar(255), timestamp BIGINT, entries varchar(32765));" -} -``` - -The function executes the query and logs the output. - -The project source includes function code and supporting resources: - -- `dbadmin` - A Node.js function that runs SQL commands for administrator use. -- `lib` - A Lambda layer with the npm modules used by the application's functions. -- `events` - JSON documents that can be used to test the application's functions. -- `template.yml` - An AWS CloudFormation template that creates the application. -- `template-vpcrds.yml` - A template that creates the VPC and Amazon RDS database instance. -- `1-create-bucket.sh`, `3-deploy-vpc.sh`, etc. - Shell scripts that use the AWS CLI to deploy and manage the application. -- bin - Additional scripts. - -Use the following instructions to deploy the sample application. - -# Requirements - -To deploy the sample application, you need the following tools: - -- [Node.js 10 with npm](https://nodejs.org/en/download/releases/). -- The Bash shell. For Linux and macOS, this is included by default. In Windows 10, you can install the [Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows-integrated version of Ubuntu and Bash. -- [The AWS CLI v1](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html). - -To run the sample application in AWS, you need permission to use Lambda and the following services. - -- Amazon RDS ([pricing](https://aws.amazon.com/rds/pricing/)) -- Amazon VPC ([pricing](https://aws.amazon.com/vpc/pricing/)) -- AWS Secrets Manager ([pricing](https://aws.amazon.com/secrets-manager/pricing/)) -- AWS X-Ray ([pricing](https://aws.amazon.com/xray/pricing/)) -- AWS Identity and Access Management -- AWS CloudFormation - -Standard charges apply for each service. - -# Setup - -Download or clone this repository. - - $ git clone https://github.com/awsdocs/aws-lambda-developer-guide.git - $ cd aws-lambda-developer-guide/sample-apps/rds-mysql - -To create a new bucket for deployment artifacts, run `1-create-bucket.sh`. - - rds-mysql$ ./1-create-bucket.sh - make_bucket: lambda-artifacts-a5e491dbb5b22e0d - -To create a database password and store it in AWS Secrets Manager, run `2-create-dbpasswordsecret.sh` script. - - rds-mysql$ ./2-create-dbpasswordsecret.sh - -To create the VPC and RDS database instance, run the `3-deploy-vpc.sh` script. This process takes about 15 minutes. - - rds-mysql$ ./3-deploy-vpc.sh - -# Deploy - -To deploy the application, run `4-deploy.sh`. - - rds-mysql$ ./4-deploy.sh - Uploading to e678bc216e6a0d510d661ca9ae2fd941 2678 / 2678.0 (100.00%) - Successfully packaged artifacts and wrote output template to file out.yml. - Waiting for changeset to be created.. - Waiting for stack create/update to complete - Successfully created/updated stack - rds-mysql - -This script uses AWS CloudFormation to deploy the Lambda functions and an IAM role. If the AWS CloudFormation stack that contains the resources already exists, the script updates it with any changes to the template or function code. - -To create a table in the database, run `5-create-dbtable.sh`. - - rds-mysql$ ./5-create-dbtable.sh - -# Test - -To invoke the function with a test event, use the invoke script. - - rds-mysql$ ./6-invoke.sh - { - "StatusCode": 200, - "ExecutedVersion": "$LATEST" - } - -Let the script invoke the function a few times and then press `CRTL+C` to exit. - -The application uses AWS X-Ray to trace requests. Open the [X-Ray console](https://console.aws.amazon.com/xray/home#/service-map) to view the service map. The following service map shows the function calling the database to run a query. - -![Service Map](/sample-apps/rds-mysql/images/rdsmysql-servicemap.png) - -Choose a node in the main function graph. Then choose **View traces** to see a list of traces. Choose any trace to view a timeline that breaks down the work done by the function. - -![Trace](/sample-apps/rds-mysql/images/rdsmysql-trace.png) - -Finally, view the application in the Lambda console. - -*To view the application* -1. Open the [applications page](https://console.aws.amazon.com/lambda/home#/applications) in the Lambda console. -2. Choose **rds-mysql**. - - ![Application](/sample-apps/rds-mysql/images/rdsmysql-application.png) - -# Cleanup - -To delete the application, run the cleanup script. - - rds-mysql$ ./8-cleanup.sh diff --git a/sample-apps/rds-mysql/bin/get-stack-event.sh b/sample-apps/rds-mysql/bin/get-stack-event.sh deleted file mode 100644 index 57e468b7..00000000 --- a/sample-apps/rds-mysql/bin/get-stack-event.sh +++ /dev/null @@ -1 +0,0 @@ -aws cloudformation describe-stack-events --stack-name list-manager --max-items 1 --query 'StackEvents[0]' diff --git a/sample-apps/rds-mysql/bin/get-stack-status.sh b/sample-apps/rds-mysql/bin/get-stack-status.sh deleted file mode 100644 index 1f8b2b5d..00000000 --- a/sample-apps/rds-mysql/bin/get-stack-status.sh +++ /dev/null @@ -1 +0,0 @@ -aws cloudformation describe-stacks --stack-name list-manager --query 'Stacks[*].StackStatus' --output text diff --git a/sample-apps/rds-mysql/dbadmin/index.js b/sample-apps/rds-mysql/dbadmin/index.js deleted file mode 100644 index b0309956..00000000 --- a/sample-apps/rds-mysql/dbadmin/index.js +++ /dev/null @@ -1,37 +0,0 @@ -var AWSXRay = require('aws-xray-sdk-core') -var captureMySQL = require('aws-xray-sdk-mysql') -var mysql = captureMySQL(require('mysql')) -const username = process.env.databaseUser -const password = process.env.databasePassword -const host = process.env.databaseHost - -exports.handler = async (event) => { - var connection = mysql.createConnection({ - host : host, - user : username, - password : password, - database : 'lambdadb' - }) - var query = event.query - var result - connection.connect() - - connection.query(query, function (error, results, fields) { - if (error) throw error - console.log("Ran query: " + query) - for (result in results) - console.log(results[result]) - }) - - return new Promise( ( resolve, reject ) => { - connection.end( err => { - if ( err ) - return reject( err ) - const response = { - statusCode: 200, - body: JSON.stringify(result), - } - resolve(response) - }) - }) -} diff --git a/sample-apps/rds-mysql/dbadmin/package.json b/sample-apps/rds-mysql/dbadmin/package.json deleted file mode 100644 index 774c74cf..00000000 --- a/sample-apps/rds-mysql/dbadmin/package.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "list-manager-processor", - "version": "1.0.0", - "private": true, - "dependencies": {}, - "devDependencies": { - "aws-xray-sdk-core": "2.4.0", - "aws-xray-sdk-mysql": "2.4.0", - "mysql": "2.17.1" - }, - "scripts": {} -} diff --git a/sample-apps/rds-mysql/events/db-add-column.json b/sample-apps/rds-mysql/events/db-add-column.json deleted file mode 100644 index 84e11d21..00000000 --- a/sample-apps/rds-mysql/events/db-add-column.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "query": "ALTER TABLE test ADD type varchar(255)" -} \ No newline at end of file diff --git a/sample-apps/rds-mysql/events/db-clear-table.json b/sample-apps/rds-mysql/events/db-clear-table.json deleted file mode 100644 index 6f0695e5..00000000 --- a/sample-apps/rds-mysql/events/db-clear-table.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "query": "DELETE FROM test" -} \ No newline at end of file diff --git a/sample-apps/rds-mysql/events/db-create-table.json b/sample-apps/rds-mysql/events/db-create-table.json deleted file mode 100644 index 4cf6499e..00000000 --- a/sample-apps/rds-mysql/events/db-create-table.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "query": "CREATE TABLE test ( id varchar(255), title varchar(255), timestamp BIGINT, entries varchar(32765));" -} \ No newline at end of file diff --git a/sample-apps/rds-mysql/events/db-drop-table.json b/sample-apps/rds-mysql/events/db-drop-table.json deleted file mode 100644 index 987f8c81..00000000 --- a/sample-apps/rds-mysql/events/db-drop-table.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "query": "DROP TABLE test" -} \ No newline at end of file diff --git a/sample-apps/rds-mysql/events/db-read-table.json b/sample-apps/rds-mysql/events/db-read-table.json deleted file mode 100644 index fb4f42cb..00000000 --- a/sample-apps/rds-mysql/events/db-read-table.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "query": "SELECT * FROM test" -} \ No newline at end of file diff --git a/sample-apps/rds-mysql/images/rdsmysql-application.png b/sample-apps/rds-mysql/images/rdsmysql-application.png deleted file mode 100644 index f45ea314..00000000 Binary files a/sample-apps/rds-mysql/images/rdsmysql-application.png and /dev/null differ diff --git a/sample-apps/rds-mysql/images/rdsmysql-servicemap.png b/sample-apps/rds-mysql/images/rdsmysql-servicemap.png deleted file mode 100644 index b93481fa..00000000 Binary files a/sample-apps/rds-mysql/images/rdsmysql-servicemap.png and /dev/null differ diff --git a/sample-apps/rds-mysql/images/rdsmysql-trace.png b/sample-apps/rds-mysql/images/rdsmysql-trace.png deleted file mode 100644 index cecd81cc..00000000 Binary files a/sample-apps/rds-mysql/images/rdsmysql-trace.png and /dev/null differ diff --git a/sample-apps/rds-mysql/images/sample-rdsmysql.png b/sample-apps/rds-mysql/images/sample-rdsmysql.png deleted file mode 100644 index c53a7aed..00000000 Binary files a/sample-apps/rds-mysql/images/sample-rdsmysql.png and /dev/null differ diff --git a/sample-apps/rds-mysql/lib/nodejs/package.json b/sample-apps/rds-mysql/lib/nodejs/package.json deleted file mode 100644 index f5859d75..00000000 --- a/sample-apps/rds-mysql/lib/nodejs/package.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "lib-layer", - "version": "1.0.0", - "private": true, - "dependencies": { - "aws-xray-sdk-core": "2.4.0", - "aws-xray-sdk-mysql": "2.4.0", - "md5": "2.2.1", - "mysql": "2.17.1" - }, - "scripts": {} -} diff --git a/sample-apps/rds-mysql/template-vpcrds.yml b/sample-apps/rds-mysql/template-vpcrds.yml deleted file mode 100644 index 378952b0..00000000 --- a/sample-apps/rds-mysql/template-vpcrds.yml +++ /dev/null @@ -1,125 +0,0 @@ -AWSTemplateFormatVersion: 2010-09-09 -Parameters: - databaseName: - Default: lambdadb - Description: Database name - Type: String - MinLength: '1' - MaxLength: '64' - AllowedPattern: '[a-zA-Z][a-zA-Z0-9]*' - ConstraintDescription: Begin with a letter and use only alphanumeric characters. - databaseUser: - NoEcho: 'true' - Description: Database username - Default: admin - Type: String - MinLength: '1' - MaxLength: '16' - AllowedPattern: '[a-zA-Z][a-zA-Z0-9]*' - ConstraintDescription: Begin with a letter and use only alphanumeric characters. -Resources: - databaseSubnetGroup: - Type: AWS::RDS::DBSubnetGroup - Properties: - DBSubnetGroupDescription: Subnets - SubnetIds: - - !Ref privateSubnetA - - !Ref privateSubnetB - database: - Type: AWS::RDS::DBInstance - Properties: - DBName: !Ref databaseName - AllocatedStorage: '10' - DBInstanceClass: db.t3.small - Engine: MySQL - EngineVersion: 5.7.26 - MasterUsername: !Ref 'databaseUser' - MasterUserPassword: '{{resolve:secretsmanager:rds-mysql-admin:SecretString:password}}' - DeletionProtection: true - MultiAZ: true - DBSubnetGroupName: !Ref databaseSubnetGroup - VPCSecurityGroups: - - !GetAtt privateVPC.DefaultSecurityGroup - privateVPC: - Type: AWS::EC2::VPC - Properties: - CidrBlock: 172.31.0.0/16 - Tags: - - Key: Name - Value: !Ref AWS::StackName - privateSubnetA: - Type: AWS::EC2::Subnet - Properties: - VpcId: !Ref privateVPC - AvailabilityZone: - Fn::Select: - - 0 - - Fn::GetAZs: "" - CidrBlock: 172.31.3.0/24 - MapPublicIpOnLaunch: false - Tags: - - Key: Name - Value: !Join ["-", [!Ref "AWS::StackName","subnet-a"]] - privateSubnetB: - Type: AWS::EC2::Subnet - Properties: - VpcId: !Ref privateVPC - AvailabilityZone: - Fn::Select: - - 1 - - Fn::GetAZs: "" - CidrBlock: 172.31.2.0/24 - MapPublicIpOnLaunch: false - Tags: - - Key: Name - Value: !Join ["-", [!Ref "AWS::StackName","subnet-b"]] - privateRouteTable: - Type: AWS::EC2::RouteTable - Properties: - VpcId: !Ref privateVPC - privateSubnetARouteTableAssociation: - Type: AWS::EC2::SubnetRouteTableAssociation - Properties: - SubnetId: !Ref privateSubnetA - RouteTableId: !Ref privateRouteTable - privateSubnetBRouteTableAssociation: - Type: AWS::EC2::SubnetRouteTableAssociation - Properties: - SubnetId: !Ref privateSubnetB - RouteTableId: !Ref privateRouteTable -Outputs: - privateVPCSecurityGroup: - Description: Default security for Lambda VPC - Value: !GetAtt privateVPC.DefaultSecurityGroup - Export: - Name: !Join ["-", [!Ref "AWS::StackName","vpc-sg"]] - privateVPCID: - Description: VPC ID - Value: !Ref privateVPC - Export: - Name: !Join ["-", [!Ref "AWS::StackName","vpc"]] - privateSubnetAID: - Description: Private Subnet A ID - Value: !Ref privateSubnetA - Export: - Name: !Join ["-", [!Ref "AWS::StackName","subnet-a"]] - privateSubnetBID: - Description: Private Subnet B ID - Value: !Ref privateSubnetB - Export: - Name: !Join ["-", [!Ref "AWS::StackName","subnet-b"]] - databaseHost: - Description: Database hostname - Value: !GetAtt database.Endpoint.Address - Export: - Name: !Join ["-", [!Ref "AWS::StackName","db-host"]] - databaseName: - Description: Database name - Value: !Ref databaseName - Export: - Name: !Join ["-", [!Ref "AWS::StackName","db-name"]] - databaseUser: - Description: Database user - Value: !Ref databaseUser - Export: - Name: !Join ["-", [!Ref "AWS::StackName","db-user"]] diff --git a/sample-apps/rds-mysql/template.yml b/sample-apps/rds-mysql/template.yml deleted file mode 100644 index a81c1f4a..00000000 --- a/sample-apps/rds-mysql/template.yml +++ /dev/null @@ -1,61 +0,0 @@ -AWSTemplateFormatVersion: 2010-09-09 -Description: An AWS Lambda application that connects to a MySQL database in the VPC to run SQL queries. -Transform: AWS::Serverless-2016-10-31 -Parameters: - vpcStackName: - Default: rds-mysql-vpc - Description: VPC and database stack name - Type: String - secretName: - Default: rds-mysql-admin - Description: Database password secret name - Type: String -Globals: - Function: - Runtime: nodejs12.x - Tracing: Active - Handler: index.handler - Environment: - Variables: - databaseHost: - Fn::ImportValue: - !Sub "${vpcStackName}-db-host" - databaseName: - Fn::ImportValue: - !Sub "${vpcStackName}-db-name" - databaseUser: - Fn::ImportValue: - !Sub "${vpcStackName}-db-user" - databasePassword: !Sub '{{resolve:secretsmanager:${secretName}:SecretString:password}}' - VpcConfig: - SecurityGroupIds: - - Fn::ImportValue: - !Sub "${vpcStackName}-vpc-sg" - SubnetIds: - - Fn::ImportValue: - !Sub "${vpcStackName}-subnet-a" - - Fn::ImportValue: - !Sub "${vpcStackName}-subnet-b" - Layers: - - !Ref libs -Resources: - libs: - Type: AWS::Serverless::LayerVersion - Properties: - LayerName: rds-mysql-lib - Description: Dependencies for the rds-mysql sample app. - ContentUri: lib/. - CompatibleRuntimes: - - nodejs10.x - - nodejs12.x - dbadmin: - Type: AWS::Serverless::Function - Properties: - CodeUri: dbadmin/. - Description: Run SQL queries. - MemorySize: 128 - Timeout: 15 - # Function's execution role - Policies: - - AWSLambdaBasicExecutionRole - - AWSLambdaVPCAccessExecutionRole diff --git a/sample-apps/s3-java/2-build-layer.sh b/sample-apps/s3-java/2-build-layer.sh index 6483568e..621eb256 100755 --- a/sample-apps/s3-java/2-build-layer.sh +++ b/sample-apps/s3-java/2-build-layer.sh @@ -1,4 +1,4 @@ #!/bin/bash set -eo pipefail -gradle -q packageLibs +gradle -q packageJar mv build/distributions/s3-java.zip build/s3-java-lib.zip \ No newline at end of file diff --git a/sample-apps/s3-java/5-invoke.sh b/sample-apps/s3-java/5-invoke.sh index d65db099..9399b6ca 100755 --- a/sample-apps/s3-java/5-invoke.sh +++ b/sample-apps/s3-java/5-invoke.sh @@ -9,7 +9,7 @@ if [ ! -f event.json ]; then fi while true; do - aws lambda invoke --function-name $FUNCTION --payload file://event.json out.json + aws lambda invoke --function-name $FUNCTION --payload fileb://event.json out.json cat out.json echo "" sleep 2 diff --git a/sample-apps/s3-java/README.md b/sample-apps/s3-java/README.md index 407063bf..55601044 100644 --- a/sample-apps/s3-java/README.md +++ b/sample-apps/s3-java/README.md @@ -4,7 +4,7 @@ The project source includes function code and supporting resources: -- `src/main` - A Java function. +- `src/main` - A Java Lambda function that scales down an image stored in S3. - `src/test` - A unit test and helper classes. - `template.yml` - An AWS CloudFormation template that creates an application. - `build.gradle` - A Gradle build file. @@ -14,10 +14,10 @@ The project source includes function code and supporting resources: Use the following instructions to deploy the sample application. # Requirements -- [Java 8 runtime environment (SE JRE)](https://www.oracle.com/java/technologies/javase-downloads.html) -- [Gradle 5](https://gradle.org/releases/) +- [Java 21 runtime environment (SE JRE)](https://www.oracle.com/java/technologies/javase-downloads.html) +- [Gradle 5](https://gradle.org/releases/) or [Maven 3](https://maven.apache.org/docs/history.html) - The Bash shell. For Linux and macOS, this is included by default. In Windows 10, you can install the [Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows-integrated version of Ubuntu and Bash. -- [The AWS CLI v1](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html). +- [The AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html) v1.17 or newer. # Setup Download or clone this repository. @@ -55,10 +55,14 @@ You can also build the application with Maven. To use maven, add `mvn` to the co ... # Test -To upload an image file to the application bucket and trigger the function, run `4-upload.sh`. +This Lambda function takes an image that's currently stored in S3, and scales it down into +a thumbnail-sized image. To upload an image file to the application bucket, run `4-upload.sh`. s3-java$ ./4-upload.sh +In your `s3-java-bucket-` bucket that was created in step 3, you should now see a +key `inbound/sample-s3-java.png` file, which represents the original image. + To invoke the function directly, run `5-invoke.sh`. s3-java$ ./5-invoke.sh @@ -69,6 +73,9 @@ To invoke the function directly, run `5-invoke.sh`. Let the script invoke the function a few times and then press `CRTL+C` to exit. +If you look at the `s3-java-bucket-` bucket in your account, you should now see a +key `resized-inbound/sample-s3-java.png` file, which represents the new, shrunken image. + The application uses AWS X-Ray to trace requests. Open the [X-Ray console](https://console.aws.amazon.com/xray/home#/service-map) to view the service map. ![Service Map](/sample-apps/s3-java/images/s3-java-servicemap.png) diff --git a/sample-apps/s3-java/build.gradle b/sample-apps/s3-java/build.gradle index 2ab2d35a..d1029343 100644 --- a/sample-apps/s3-java/build.gradle +++ b/sample-apps/s3-java/build.gradle @@ -7,18 +7,15 @@ repositories { } dependencies { - implementation platform('com.amazonaws:aws-xray-recorder-sdk-bom:2.4.0') - implementation 'com.amazonaws:aws-lambda-java-core:1.2.0' - implementation 'com.amazonaws:aws-lambda-java-events:2.2.7' - implementation 'com.amazonaws:aws-java-sdk-s3:1.11.578' + implementation platform('software.amazon.awssdk:bom:2.16.1') + implementation platform('com.amazonaws:aws-xray-recorder-sdk-bom:2.11.0') + implementation 'software.amazon.awssdk:s3' + implementation 'com.amazonaws:aws-lambda-java-core:1.2.1' + implementation 'com.amazonaws:aws-lambda-java-events:3.11.0' implementation 'com.amazonaws:aws-xray-recorder-sdk-core' implementation 'com.amazonaws:aws-xray-recorder-sdk-aws-sdk' - implementation 'com.amazonaws:aws-xray-recorder-sdk-aws-sdk-instrumentor' - implementation 'com.google.code.gson:gson:2.8.6' - implementation 'org.apache.logging.log4j:log4j-api:2.13.0' - implementation 'org.apache.logging.log4j:log4j-core:2.13.0' - implementation 'org.apache.logging.log4j:log4j-slf4j18-impl:2.13.0' - runtimeOnly 'com.amazonaws:aws-lambda-java-log4j2:1.1.0' + implementation 'com.amazonaws:aws-xray-recorder-sdk-aws-sdk-v2-instrumentor' + implementation 'org.slf4j:slf4j-nop:2.0.6' testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.6.0' } @@ -27,28 +24,16 @@ test { useJUnitPlatform() } -task packageBig(type: Zip) { - from compileJava - from processResources +task packageJar(type: Zip) { into('lib') { - from configurations.runtimeClasspath + from(jar) + from(configurations.runtimeClasspath) } } -task packageLibs(type: Zip) { - into('java/lib') { - from configurations.runtimeClasspath - } -} - -task packageSmall(type: Zip) { - from compileJava - from processResources -} - java { - sourceCompatibility = JavaVersion.VERSION_1_8 - targetCompatibility = JavaVersion.VERSION_1_8 + sourceCompatibility = JavaVersion.VERSION_21 + targetCompatibility = JavaVersion.VERSION_21 } -build.dependsOn packageSmall +build.dependsOn packageJar diff --git a/sample-apps/java-events-v1sdk/event.json b/sample-apps/s3-java/event.json-e similarity index 95% rename from sample-apps/java-events-v1sdk/event.json rename to sample-apps/s3-java/event.json-e index 94c28f5c..375e90ab 100644 --- a/sample-apps/java-events-v1sdk/event.json +++ b/sample-apps/s3-java/event.json-e @@ -23,7 +23,7 @@ "arn": "arn:aws:s3:::BUCKET_NAME" }, "object": { - "key": "inbound/sample-java-s3.png", + "key": "inbound/sample-s3-java.png", "size": 21476, "eTag": "d132690b6c65b6d1629721dcfb49b883", "versionId": "", diff --git a/sample-apps/s3-java/pom.xml b/sample-apps/s3-java/pom.xml index ce4b7f06..c8099a40 100644 --- a/sample-apps/s3-java/pom.xml +++ b/sample-apps/s3-java/pom.xml @@ -8,69 +8,60 @@ s3-java-function UTF-8 - 1.8 - 1.8 + 21 + 21 + + + + + software.amazon.awssdk + bom + 2.16.1 + pom + import + + + com.amazonaws + aws-xray-recorder-sdk-bom + 2.11.0 + pom + import + + + + - com.amazonaws - aws-lambda-java-core - 1.2.0 + software.amazon.awssdk + s3 com.amazonaws - aws-lambda-java-events - 2.2.7 - - - com.amazonaws - aws-lambda-java-log4j2 - 1.1.0 - - - com.google.code.gson - gson - 2.8.6 - - - org.apache.logging.log4j - log4j-api - 2.13.0 - - - org.apache.logging.log4j - log4j-core - 2.13.0 - - - org.apache.logging.log4j - log4j-slf4j18-impl - 2.13.0 + aws-lambda-java-core + 1.2.1 com.amazonaws - aws-java-sdk-s3 - 1.11.578 + aws-lambda-java-events + 3.11.0 com.amazonaws aws-xray-recorder-sdk-core - 2.4.0 com.amazonaws - aws-xray-recorder-sdk-aws-sdk-core - 2.4.0 + aws-xray-recorder-sdk-aws-sdk com.amazonaws - aws-xray-recorder-sdk-aws-sdk - 2.4.0 + aws-xray-recorder-sdk-aws-sdk-v2-instrumentor - com.amazonaws - aws-xray-recorder-sdk-aws-sdk-instrumentor - 2.4.0 + org.slf4j + slf4j-nop + 2.0.13 org.junit.jupiter @@ -95,7 +86,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.2.2 + 3.5.2 false @@ -105,29 +96,17 @@ shade - - - - - -
- - - com.github.edwgiz - maven-shade-plugin.log4j2-cachefile-transformer - 2.13.0 - - org.apache.maven.plugins maven-compiler-plugin - 3.8.1 + 3.13.0 - 1.8 - 1.8 + 21 + 21 + 21 diff --git a/sample-apps/s3-java/src/main/java/example/Handler.java b/sample-apps/s3-java/src/main/java/example/Handler.java index 829ceeb4..e4c14c4d 100644 --- a/sample-apps/s3-java/src/main/java/example/Handler.java +++ b/sample-apps/s3-java/src/main/java/example/Handler.java @@ -4,46 +4,40 @@ import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; -import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.imageio.ImageIO; -import com.amazonaws.AmazonServiceException; +import software.amazon.awssdk.awscore.exception.AwsServiceException; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.S3Client; + import com.amazonaws.services.lambda.runtime.Context; +import com.amazonaws.services.lambda.runtime.LambdaLogger; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.S3Event; -import com.amazonaws.services.s3.AmazonS3; -import com.amazonaws.services.s3.event.S3EventNotification.S3EventNotificationRecord; -import com.amazonaws.services.s3.model.GetObjectRequest; -import com.amazonaws.services.s3.model.ObjectMetadata; -import com.amazonaws.services.s3.model.S3Object; -import com.amazonaws.services.s3.AmazonS3ClientBuilder; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import com.amazonaws.services.lambda.runtime.events.models.s3.S3EventNotification.S3EventNotificationRecord; // Handler value: example.Handler public class Handler implements RequestHandler { - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - private static final Logger logger = LoggerFactory.getLogger(Handler.class); - private static final float MAX_WIDTH = 100; - private static final float MAX_HEIGHT = 100; - private final String JPG_TYPE = (String) "jpg"; - private final String JPG_MIME = (String) "image/jpeg"; - private final String PNG_TYPE = (String) "png"; - private final String PNG_MIME = (String) "image/png"; + private static final float MAX_DIMENSION = 100; + private final String REGEX = ".*\\.([^\\.]*)"; + private final String JPG_TYPE = "jpg"; + private final String JPG_MIME = "image/jpeg"; + private final String PNG_TYPE = "png"; + private final String PNG_MIME = "image/png"; @Override public String handleRequest(S3Event s3event, Context context) { + LambdaLogger logger = context.getLogger(); try { - logger.info("EVENT: " + gson.toJson(s3event)); S3EventNotificationRecord record = s3event.getRecords().get(0); String srcBucket = record.getS3().getBucket().getName(); @@ -55,75 +49,108 @@ public String handleRequest(S3Event s3event, Context context) { String dstKey = "resized-" + srcKey; // Infer the image type. - Matcher matcher = Pattern.compile(".*\\.([^\\.]*)").matcher(srcKey); + Matcher matcher = Pattern.compile(REGEX).matcher(srcKey); if (!matcher.matches()) { - logger.info("Unable to infer image type for key " + srcKey); + logger.log("Unable to infer image type for key " + srcKey); return ""; } String imageType = matcher.group(1); if (!(JPG_TYPE.equals(imageType)) && !(PNG_TYPE.equals(imageType))) { - logger.info("Skipping non-image " + srcKey); + logger.log("Skipping non-image " + srcKey); return ""; } // Download the image from S3 into a stream - AmazonS3 s3Client = AmazonS3ClientBuilder.defaultClient(); - S3Object s3Object = s3Client.getObject(new GetObjectRequest( - srcBucket, srcKey)); - InputStream objectData = s3Object.getObjectContent(); - - // Read the source image - BufferedImage srcImage = ImageIO.read(objectData); - int srcHeight = srcImage.getHeight(); - int srcWidth = srcImage.getWidth(); - // Infer the scaling factor to avoid stretching the image - // unnaturally - float scalingFactor = Math.min(MAX_WIDTH / srcWidth, MAX_HEIGHT - / srcHeight); - int width = (int) (scalingFactor * srcWidth); - int height = (int) (scalingFactor * srcHeight); - - BufferedImage resizedImage = new BufferedImage(width, height, - BufferedImage.TYPE_INT_RGB); - Graphics2D g = resizedImage.createGraphics(); - // Fill with white before applying semi-transparent (alpha) images - g.setPaint(Color.white); - g.fillRect(0, 0, width, height); - // Simple bilinear resize - g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, - RenderingHints.VALUE_INTERPOLATION_BILINEAR); - g.drawImage(srcImage, 0, 0, width, height, null); - g.dispose(); + S3Client s3Client = S3Client.builder().build(); + InputStream s3Object = getObject(s3Client, srcBucket, srcKey); + + // Read the source image and resize it + BufferedImage srcImage = ImageIO.read(s3Object); + BufferedImage newImage = resizeImage(srcImage); // Re-encode image to target format - ByteArrayOutputStream os = new ByteArrayOutputStream(); - ImageIO.write(resizedImage, imageType, os); - InputStream is = new ByteArrayInputStream(os.toByteArray()); - // Set Content-Length and Content-Type - ObjectMetadata meta = new ObjectMetadata(); - meta.setContentLength(os.size()); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + ImageIO.write(newImage, imageType, outputStream); + + // Upload new image to S3 + putObject(s3Client, outputStream, dstBucket, dstKey, imageType, logger); + + logger.log("Successfully resized " + srcBucket + "/" + + srcKey + " and uploaded to " + dstBucket + "/" + dstKey); + return "Ok"; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private InputStream getObject(S3Client s3Client, String bucket, String key) { + GetObjectRequest getObjectRequest = GetObjectRequest.builder() + .bucket(bucket) + .key(key) + .build(); + return s3Client.getObject(getObjectRequest); + } + + private void putObject(S3Client s3Client, ByteArrayOutputStream outputStream, + String bucket, String key, String imageType, LambdaLogger logger) { + Map metadata = new HashMap<>(); + metadata.put("Content-Length", Integer.toString(outputStream.size())); if (JPG_TYPE.equals(imageType)) { - meta.setContentType(JPG_MIME); - } - if (PNG_TYPE.equals(imageType)) { - meta.setContentType(PNG_MIME); + metadata.put("Content-Type", JPG_MIME); + } else if (PNG_TYPE.equals(imageType)) { + metadata.put("Content-Type", PNG_MIME); } + PutObjectRequest putObjectRequest = PutObjectRequest.builder() + .bucket(bucket) + .key(key) + .metadata(metadata) + .build(); + // Uploading to S3 destination bucket - logger.info("Writing to: " + dstBucket + "/" + dstKey); + logger.log("Writing to: " + bucket + "/" + key); try { - s3Client.putObject(dstBucket, dstKey, is, meta); + s3Client.putObject(putObjectRequest, + RequestBody.fromBytes(outputStream.toByteArray())); } - catch(AmazonServiceException e) + catch(AwsServiceException e) { - logger.error(e.getErrorMessage()); + logger.log(e.awsErrorDetails().errorMessage()); System.exit(1); } - logger.info("Successfully resized " + srcBucket + "/" - + srcKey + " and uploaded to " + dstBucket + "/" + dstKey); - return "Ok"; - } catch (IOException e) { - throw new RuntimeException(e); - } + } + + /** + * Resizes (shrinks) an image into a small, thumbnail-sized image. + * + * The new image is scaled down proportionally based on the source + * image. The scaling factor is determined based on the value of + * MAX_DIMENSION. The resulting new image has max(height, width) + * = MAX_DIMENSION. + * + * @param srcImage BufferedImage to resize. + * @return New BufferedImage that is scaled down to thumbnail size. + */ + private BufferedImage resizeImage(BufferedImage srcImage) { + int srcHeight = srcImage.getHeight(); + int srcWidth = srcImage.getWidth(); + // Infer scaling factor to avoid stretching image unnaturally + float scalingFactor = Math.min( + MAX_DIMENSION / srcWidth, MAX_DIMENSION / srcHeight); + int width = (int) (scalingFactor * srcWidth); + int height = (int) (scalingFactor * srcHeight); + + BufferedImage resizedImage = new BufferedImage(width, height, + BufferedImage.TYPE_INT_RGB); + Graphics2D graphics = resizedImage.createGraphics(); + // Fill with white before applying semi-transparent (alpha) images + graphics.setPaint(Color.white); + graphics.fillRect(0, 0, width, height); + // Simple bilinear resize + graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, + RenderingHints.VALUE_INTERPOLATION_BILINEAR); + graphics.drawImage(srcImage, 0, 0, width, height, null); + graphics.dispose(); + return resizedImage; } } \ No newline at end of file diff --git a/sample-apps/s3-java/src/test/java/example/InvokeTest.java b/sample-apps/s3-java/src/test/java/example/InvokeTest.java index 8e090042..3578296e 100644 --- a/sample-apps/s3-java/src/test/java/example/InvokeTest.java +++ b/sample-apps/s3-java/src/test/java/example/InvokeTest.java @@ -1,28 +1,18 @@ package example; -import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.LambdaLogger; -import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.S3Event; -import com.amazonaws.services.s3.event.S3EventNotification; -import com.amazonaws.services.s3.event.S3EventNotification.S3EventNotificationRecord; -import com.amazonaws.services.s3.event.S3EventNotification.RequestParametersEntity; -import com.amazonaws.services.s3.event.S3EventNotification.ResponseElementsEntity; -import com.amazonaws.services.s3.event.S3EventNotification.S3Entity; -import com.amazonaws.services.s3.event.S3EventNotification.UserIdentityEntity; -import com.amazonaws.services.s3.event.S3EventNotification.GlacierEventDataEntity; -import com.amazonaws.services.s3.event.S3EventNotification.S3BucketEntity; -import com.amazonaws.services.s3.event.S3EventNotification.S3ObjectEntity; -import com.amazonaws.services.s3.event.S3EventNotification.UserIdentityEntity; +import com.amazonaws.services.lambda.runtime.events.models.s3.S3EventNotification.RequestParametersEntity; +import com.amazonaws.services.lambda.runtime.events.models.s3.S3EventNotification.ResponseElementsEntity; +import com.amazonaws.services.lambda.runtime.events.models.s3.S3EventNotification.S3BucketEntity; +import com.amazonaws.services.lambda.runtime.events.models.s3.S3EventNotification.S3Entity; +import com.amazonaws.services.lambda.runtime.events.models.s3.S3EventNotification.S3EventNotificationRecord; +import com.amazonaws.services.lambda.runtime.events.models.s3.S3EventNotification.S3ObjectEntity; +import com.amazonaws.services.lambda.runtime.events.models.s3.S3EventNotification.UserIdentityEntity; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.List; import java.util.ArrayList; import java.lang.Long; import java.nio.file.Files; @@ -34,7 +24,6 @@ import com.amazonaws.xray.strategy.sampling.NoSamplingStrategy; class InvokeTest { - private static final Logger logger = LoggerFactory.getLogger(InvokeTest.class); public InvokeTest() { AWSXRayRecorderBuilder builder = AWSXRayRecorderBuilder.standard(); @@ -69,7 +58,6 @@ void invokeTest() throws IOException { S3Event event = new S3Event(records); Context context = new TestContext(); - String requestId = context.getAwsRequestId(); Handler handler = new Handler(); String result = handler.handleRequest(event, context); assertTrue(result.contains("Ok")); diff --git a/sample-apps/s3-java/template-mvn.yml b/sample-apps/s3-java/template-mvn.yml index e8e77b37..32eab63d 100644 --- a/sample-apps/s3-java/template-mvn.yml +++ b/sample-apps/s3-java/template-mvn.yml @@ -10,14 +10,14 @@ Resources: Properties: CodeUri: target/s3-java-1.0-SNAPSHOT.jar Handler: example.Handler::handleRequest - Runtime: java8 + Runtime: java21 Description: Java function MemorySize: 512 - Timeout: 10 + Timeout: 30 # Function's execution role Policies: - AWSLambdaBasicExecutionRole - - AWSLambdaReadOnlyAccess + - AWSLambda_ReadOnlyAccess - AWSXrayWriteOnlyAccess - AWSLambdaVPCAccessExecutionRole - AmazonS3FullAccess @@ -32,4 +32,4 @@ Resources: S3Key: Rules: - Name: prefix - Value: inbound/ \ No newline at end of file + Value: inbound/ diff --git a/sample-apps/s3-java/template.yml b/sample-apps/s3-java/template.yml index 3ffd1620..58189a55 100644 --- a/sample-apps/s3-java/template.yml +++ b/sample-apps/s3-java/template.yml @@ -10,14 +10,14 @@ Resources: Properties: CodeUri: build/distributions/s3-java.zip Handler: example.Handler - Runtime: java8 + Runtime: java21 Description: Java function MemorySize: 512 - Timeout: 10 + Timeout: 30 # Function's execution role Policies: - AWSLambdaBasicExecutionRole - - AWSLambdaReadOnlyAccess + - AWSLambda_ReadOnlyAccess - AWSXrayWriteOnlyAccess - AWSLambdaVPCAccessExecutionRole - AmazonS3FullAccess @@ -42,4 +42,4 @@ Resources: Description: Dependencies for the Java S3 sample app. ContentUri: build/s3-java-lib.zip CompatibleRuntimes: - - java8 \ No newline at end of file + - java21 diff --git a/templates/create-stack.sh b/templates/create-stack.sh new file mode 100755 index 00000000..36dc0332 --- /dev/null +++ b/templates/create-stack.sh @@ -0,0 +1,27 @@ +#!/bin/bash +set -eo pipefail +if [[ $# -gt 1 ]]; then + TEMPLATE_NAME=$1 + shift + OVERRIDES="$@" + OVERRIDES_ARG="--parameter-overrides ${OVERRIDES}" + TEMPLATE=$(cat ${TEMPLATE_NAME}.yml) +elif [[ $# -eq 1 ]]; then + TEMPLATE_NAME=$1 + TEMPLATE=$(cat ${TEMPLATE_NAME}.yml) + if [[ "$TEMPLATE" =~ PLACEHOLDER ]]; then + echo "Usage: ./create-stack.sh " + echo "e.g. ./create-stack.sh my-template parameter=value parameter2=value2" + exit 0 + fi +else + echo "Usage: ./create-stack.sh " + echo "e.g. ./create-stack.sh function-inline" + echo "e.g. ./create-stack.sh my-template parameter=value parameter2=value2" + exit 0 +fi +STACK_NAME=lambda-${TEMPLATE_NAME} +if [[ "$TEMPLATE" =~ "AWS::IAM::Role" ]]; then + CAPA_ARG="--capabilities CAPABILITY_NAMED_IAM" +fi +aws cloudformation deploy --template-file ${TEMPLATE_NAME}.yml --stack-name ${STACK_NAME} ${CAPA_ARG} ${OVERRIDES_ARG} \ No newline at end of file diff --git a/templates/delete-stack.sh b/templates/delete-stack.sh new file mode 100755 index 00000000..0496d389 --- /dev/null +++ b/templates/delete-stack.sh @@ -0,0 +1,18 @@ +#!/bin/bash +set -eo pipefail +if [[ $# -eq 1 ]]; then + TEMPLATE_NAME=$1 +else + echo "Usage: ./delete-stack.sh " + echo "e.g. ./delete-stack.sh function-inline" + exit 0 +fi +STACK_NAME=lambda-${TEMPLATE_NAME} +while true; do + read -p "Delete stack ${STACK_NAME}? (y/n)" response + case $response in + [Yy]* ) aws cloudformation delete-stack --stack-name ${STACK_NAME}; break;; + [Nn]* ) break;; + * ) echo "Response must start with y or n.";; + esac +done \ No newline at end of file diff --git a/templates/function-inline.yml b/templates/function-inline.yml index b1ddaf7a..cf2537ff 100644 --- a/templates/function-inline.yml +++ b/templates/function-inline.yml @@ -29,7 +29,7 @@ Resources: Handler: index.handler MemorySize: 128 Role: !GetAtt executionRole.Arn - Runtime: nodejs12.x + Runtime: nodejs16.x Timeout: 10 TracingConfig: Mode: Active